javascript - JS 方向更改监听器不会在 iOS 上触发,但在 Android 上会触发

标签 javascript ios iphone orientation screen-orientation

我有这个代码:

window.addEventListener("orientationchange", orientation);

但它不会在运行 iOS 10.3 的 iPhone SE 上触发 orientation(),但它会在运行 Android 5.1 的 Moto G 上触发。

我需要它来更新取决于屏幕宽度的内容。如果未定义(浏览器差异),我使用 window.innerWidthscreen.width

我的 orientation() 如下:

cpr = Math.floor(window.innerWidth/100) - 3;
if (navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Android/i)) cpr = Math.min(Math.floor(screen.width/100) - 1, 8);
if (!cpr || cpr <= 0) cpr = 1;
id('times').innerHTML = "";
updateTimes();

代码工作正常,只是在 iOS 上不工作。我在 Chrome 开发工具设备查看器中进行了尝试,它允许您使用不同的特定手机或设备来测试屏幕尺寸和浏览器/设备样式/代码/用户代理。它在那里工作得很好。

我尝试查看有关此问题的所有其他 Stack Overflow 问题,但它们没有回答我的问题。

您可以在 http://rucubing.bitballoon.com 查看网站看看它是如何工作的。

谢谢!

最佳答案

我对调整大小事件也有类似的问题。 我在 this page 上找到了原因.

Up until recently Mobile Safari has correctly posted the resize event after the viewport was resized and after page layout. However, that’s no longer the case. Instead it’s posted before the page has been completely laid out. Any JavaScript relying on clientWidth, clientHeight, getBoundingClientRect etc. in an onresize callback is now broken.

可能在页面完全布局之前也触发了 orientationchange 事件,所以 window.innerWidth 返回了错误的值。

编辑:

最近我发现 document.documentElement.clientWidth 返回正确的值。也许这可以帮助你。

关于javascript - JS 方向更改监听器不会在 iOS 上触发,但在 Android 上会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441339/

相关文章:

iphone - 如何覆盖plist文件的内容? (iPhone/iPad)

javascript - 将函数传递给 React Component 然后调用它会导致 "Uncaught TypeError: x is not a function"

Javascript更改位置href并单击某个按钮

javascript - 很奇怪!调用 window.location 或 location.replace 会重定向到该页面,然后再次返回!

ios - 在测试期间绕过或模拟 Apple 权限对话框

ios - swift : Subclassing SlackTextViewController in tableview

javascript - Mootools:拒绝设置不安全 header "Connection"

ios - 如何在 NSUserDefaults 中保存和检索 double 组?

ios - 无法使用 XMPPFramework 连接到远程服务器

android - 如何拦截来自 Android/iOS 应用程序的更新/通知