javascript - 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);
推荐阅读
- java - 我的自定义视图不会加载
- sails.js - 模型属性类型:json和ref有什么区别?
- java - JPanel 部分脱离了 JFrame
- javascript - 类型元素上不存在属性 attachshadow
- c++ - 如何在多进程 Win32 应用程序中处理 WM_QUERYENDSESSION 消息?
- c# - Dynamics CRM sdk - 使用 Helper 代码连接
- apache - 为动态端口创建 Apache 反向代理
- php - Bootstrap 4导航栏大于视口
- javascript - express js中路由路径与assets或public文件夹有什么关系?
- c# - C# Unity - Roguelike 房间生成