I am trying to accurately capture the window height and width of a mobile browser when the orientation changes, but (in Android, I'm testing) - when the orientation listener fires and the function is called to capture the window height and width, the new size has not yet accurately been reflected, so I end up having to call an arbitrary delay to get things to registe开发者_JAVA技巧r their proper size. How do I handle this? Here's my code:
window.addEventListener(orientationEvent, function() {
setTimeout("setViewport()", 500);
//setViewport();
}, false);
function setViewport() { //Called each time orientation changes, including initial orientation
viewportW = window.innerWidth; //only reports the accurate window size if the function is called on a delay
viewportH = window.innerHeight;
}
Use the resize event instead
window.addEventListener('resize', function() {
viewportW = window.innerWidth;
viewportH = window.innerHeight;
}, false);
In case you want to particularly change those values only when orientation changes, you can use window.matchMedia to verify the orientation also changed :
var portrait=(window.matchMedia("(orientation: portrait)")?true:false);
精彩评论