Mobile viewport height after orientation change

2019-01-25 04:14发布

I am attaching a listener to the orientationchange event:

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

I need to get the height of the document after the orientationchange. However, the event is triggered before the rotation is complete. Therefore, the recorded height reflects the state before the actual orientation change.

How do I register an event that would allow me to capture element dimensions after the orientation change has been completed?

7条回答
啃猪蹄的小仙女
2楼-- · 2019-01-25 04:34

For people who just want the innerHeight of the window object after the orientationchange there is a simple solution. Use window.innerWidth. The innerWidth during the orientationchange event is the innerHeight after completion of the orientationchange:

window.addEventListener('orientationchange', function () {
    var innerHeightAfterEvent = window.innerWidth;
    console.log(innerHeightAfterEvent);
    var innerWidthAfterEvent = window.innerHeight;
    console.log(innerWidthAfterEvent);
    console.log(screen.orientation.angle);
});

I am not sure if 180-degree changes are done in two 90 degree steps or not. Can't simulate that in the browser with the help of developer tools. But If you want to safeguard against a full 180, 270 or 360 rotation possibility it should be possible to use screen.orientation.angle to calculate the angle and use the correct height and width. The screen.orientation.angle during the event is the target angle of the orientationchange event.

查看更多
登录 后发表回答