JavaScript 屏幕旋转后获取浏览器宽高

JavaScript About 872 words

问题

旋转事件中获得的浏览器宽高window.innerHeightwindow.innerWidth或者document.body.clientHeightdocument.body.clientWidth是选择之前的宽高。

解决

可以使用延迟获取的方法。

示例

var body = document.documentElement || document.body;
if ("onorientationchange" in window) {
    window.onorientationchange = onScreenRotate;
} else if ("screen" in window && "orientation" in window.screen) {
    window.screen.orientation.addEventListener("change", onScreenRotate);
}

function onScreenRotate(event) {
    setTimeout(function () {
        document.getElementById("init").innerText = "body.clientWidth#" + body.clientWidth + ", body.clientHeight#" + body.clientHeight;
        document.getElementById("status").innerText = screen.orientation.type;
    }, 200)

}

备注

如果只在移动设备上使用该API,且不考虑Android的分屏、小窗,Surface设备上的拖动边框,可以使用window.screen.widthwindow.screen.heightwindow.screen.availWidthwindow.screen.availHeight

Views: 1,767 · Posted: 2021-06-27

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh