如何解决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
在横向时显示,而在纵向时隐藏,这基本上与我阅读时的代码完全相反。
有人知道这个问题吗,知道它的解决方法吗?
预先感谢
解决方法
我认为应该调用该函数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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。