开发者

android / javascript - problem with window.innerWidth and window orientationEvent firing at the right time

开发者 https://www.devze.com 2023-04-03 04:02 出处:网络
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

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消