首页 > 解决方案 > OrientationChange 行为怪异

问题描述

我有一个网站,它应该在浏览器处于纵向模式时显示图像,并在横向模式下再次隐藏它。我已经使用 chrome 响应模式测试了此功能,它运行良好,但是当尝试在 iphone 或 ipad 上运行该站点时,该功能会起作用。代码看起来像这样

let mql = window.matchMedia("(orientation: portrait)")
window.onorientationchange = rotate;

function rotate() {
    if(mql.matches) {
        document.querySelector("#rotation").classList.remove("hide");
        document.querySelector("#game").classList.add("hide");
    } else {
        document.querySelector("#rotation").classList.add("hide");
        document.querySelector("#game").classList.remove("hide");
    }
}

它在 iphone 和 ipad 上的作用方式是#rotation在横向时显示,在纵向时隐藏,这与我阅读的代码基本上完全相反。

有没有人熟悉这个问题,并且有人知道它的修复方法吗?

提前致谢

标签: javascriptiossafariorientation

解决方案


window.onorientationchange = rotate; 我认为您应该执行以下操作而不是调用该函数

let mql = window.matchMedia("(orientation: portrait)")

function rotate(event) {
    if(event.matches) {
        document.querySelector("#rotation").classList.remove("hide");
        document.querySelector("#game").classList.add("hide");
    } else {
        document.querySelector("#rotation").classList.add("hide");
        document.querySelector("#game").classList.remove("hide");
    }
}

// this addListner is going to deprecate soon
mql.addListner(rotate);
// you can use below if you don't want to support <= iOS 13 browsers
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList
mql.addEventListner("change", rotate);

推荐阅读