简体   繁体   English

OrientationChange 行为很奇怪

[英]OrientationChange acts weird

I have a website which should show an image when the browser is in portrait mode, and hide it again when in landscape.我有一个网站,它应该在浏览器处于纵向模式时显示图像,并在横向模式下再次隐藏它。 I have tested this feature with chrome responsive mode and there it acts fine, but when trying to run the site on iphone or ipad the feature acts up.我已经用 chrome 响应模式测试了这个功能,在那里它运行良好,但是当尝试在 iphone 或 ipad 上运行该网站时,该功能会起作用。 Code looks like this代码看起来像这样

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");
    }
}

The way it acts on iphone and ipad is that #rotation shows when in landscape and hides when in portrait, which is basically the total opposite of the code, as I read it.它在 iphone 和 ipad 上的作用方式是, #rotation在横向时显示,在纵向时隐藏,这基本上与我阅读的代码完全相反。

Is anyone familiar with this issue, and anyone know of a fix for it?有没有人熟悉这个问题,有没有人知道解决方法?

thanks in advance提前致谢

I think instead calling that function window.onorientationchange = rotate;我认为改为调用该函数window.onorientationchange = rotate; you should do following你应该做以下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM