Mobile viewport height after orientation change

后端 未结 10 1423
孤街浪徒
孤街浪徒 2020-12-03 04:30

I am attaching a listener to the orientationchange event:

window.addEventListener(\'orientationchange\', function () {
    console.log(window.innerHeight);
}         


        
10条回答
  •  情歌与酒
    2020-12-03 05:05

    Gajus' and burtelli's solutions are robust but the overhead is high. Here is a slim version that's reasonably fast in 2017, using requestAnimationFrame:

    // Wait until innerheight changes, for max 120 frames
    function orientationChanged() {
      const timeout = 120;
      return new window.Promise(function(resolve) {
        const go = (i, height0) => {
          window.innerHeight != height0 || i >= timeout ?
            resolve() :
            window.requestAnimationFrame(() => go(i + 1, height0));
        };
        go(0, window.innerHeight);
      });
    }
    

    Use it like this:

    window.addEventListener('orientationchange', function () {
        orientationChanged().then(function() {
          // Profit
        });
    });
    

提交回复
热议问题