javascript - 在窗口调整大小事件后调用 window.innerHeight 不会给出正确的高度

标签 javascript iphone firefox

我正在使用 window.onresize 来监听视口(viewport)大小的变化,这样我就可以适本地缩放我的内容(这是一个游戏 UI,所以使用 window.onresize + css scale 似乎最简单,欢迎提出其他建议)。

但是,在某些浏览器上,在触发 onresize 后立即调用 window.innerHeight 或 window.innerWidth 会给出错误的结果。

这是一个最小的工作示例:

<html>
  <head>
    <title>Firefox Resize bug</title>
    <link
      rel="manifest"
      href='data:application/manifest+json,{ "name": "onresize bug", "display":"standalone"}'
    />
  </head>
  <body>
    Height: <span id="heightField"></span>
    <br />
    Width: <span id="widthField"></span>
    <script>
      const heightField = document.getElementById("heightField");
      const widthField = document.getElementById("widthField");
      const updateSize = () => {
        heightField.textContent = window.innerHeight;
        widthField.textContent = window.innerWidth;
      };
      window.onresize = updateSize;
      updateSize();
    </script>
  </body>
</html>

这在 iOS 12 Safari 中运行良好,当您更改方向时,高度和宽度会正确更新。

但是,它在 iOS Firefox/Chrome 上不起作用(至少,不可靠),如果您将此应用程序添加到 iPhone 的主屏幕上,它也不起作用(参见上面示例中的 list )

我一直在通过在 onresize 事件后 500 毫秒触发我的 updateSize 来解决这个问题,但这里到底发生了什么?

最佳答案

这是 webkit 中的一个错误。

https://bugs.webkit.org/show_bug.cgi?id=185886

In iOS, the window.onresize event fires in a WKWebView when the device switches orientation. However, if the WKWebView is positioned WITH Auto Layout, window.innerWidth and window.innerHeight will report incorrect values from within the window.onresize event handler. But, if the WKWebView is positioned manually WITHOUT using Auto Layout, window.innerWidth and window.innerHeight will report correct values in the event handler.

关于javascript - 在窗口调整大小事件后调用 window.innerHeight 不会给出正确的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281142/

相关文章:

javascript - 谷歌地图上的信息窗口无法正常工作

iphone - 导航栏未显示在推送 View Controller 上

iphone - 拒绝后删除应用内购买

Angular 5 无法在 Firefox 中正确处理 301 响应

html - Div 不缩放到子图像的缩放宽度(Firefox 问题)

javascript - 如何在 Firefox 3.5 中将文本复制到剪贴板?

JavaScript RegExp 可选捕获组

javascript - 获取json字符串请求参数

javascript - d3 条形图 y 轴刻度线和高于最大值的网格线

iphone - 使用我的 iPhone 应用程序在 Facebook 墙上写一条消息