首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >iOS Chrome产生不正确的window.innerWidth和innerHeight

iOS Chrome产生不正确的window.innerWidth和innerHeight
EN

Stack Overflow用户
提问于 2022-08-25 20:32:40
回答 1查看 119关注 0票数 0

iOS上的Google 104在我旋转我的设备后报告了不正确的window.innerWidthwindow.innerHeight值。例如:

在纵向模式下加载我的页面,414 x 714.

  • I将我的手机旋转到横向,然后返回到纵向模式,然后得到390 x 334

我在下面创建了一个代码片段来测试。在出现错误的值之前,可能需要三次尝试:

代码语言:javascript
运行
复制
const $ = document.getElementById.bind(document);

const w1 = $("w1");
const h1 = $("h1");
const w2 = $("w2");
const h2 = $("h2");

// Get width/height on page load
w1.innerText = `w: ${window.innerWidth}`;
h1.innerText = `h: ${window.innerHeight}`;

// Get width/height on resize event
function onResizeInstant() {
  w2.innerText = `w: ${window.innerWidth}`;
  h2.innerText = `h: ${window.innerHeight}`;
}

window.addEventListener("resize", onResizeInstant);
代码语言:javascript
运行
复制
body{font-family: sans-serif}
h1{font-size: 16px}
div{
  font-size: 16px;
  height: 20px;
  background: #eee;
  margin-bottom: 2px;
}
代码语言:javascript
运行
复制
<h1>window.innerWidth + Height on initial page load</h1>
<div id="w1"></div>
<div id="h1"></div>

<h1>window.innerWidth + Height after rotating device</h1>
<div id="w2"></div>
<div id="h2"></div>

这在iOS Safari、、火狐或任何桌面设备上都不会发生。这种情况只发生在iOS的Google中。有谁知道这种行为的来源,或者解决这个错误的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-25 20:55:57

这绝对是一个缺陷,只有谷歌Chrome在iOS。解决方案是在读取setTimeout和window.innerHeight值之前添加一个简短的window.innerHeight()。

代码语言:javascript
运行
复制
const $ = document.getElementById.bind(document);

const w1 = $("w1");
const h1 = $("h1");
const w2 = $("w2");
const h2 = $("h2");

// Called instantly on resize event
// Could yield incorrect values on Google Chrome on iOS at random
function onResizeInstant() {
  w1.innerText = `w: ${window.innerWidth}`;
  h1.innerText = `h: ${window.innerHeight}`;
  window.setTimeout(onResizeTimeout, 5);
}

// Called after 5ms timeout
// Will yield accurate values
function onResizeTimeout() {
  w2.innerText = `w: ${window.innerWidth}`;
  h2.innerText = `h: ${window.innerHeight}`;
}

window.addEventListener("resize", onResizeInstant);

// Call on load
onResizeInstant();
代码语言:javascript
运行
复制
body{font-family: sans-serif}
h1{font-size: 16px}
div{
  font-size: 16px;
  height: 20px;
  background: #eee;
  margin-bottom: 2px;
}
代码语言:javascript
运行
复制
<h1>window.innerWidth + Height before setTimeout()</h1>
<div id="w1"></div>
<div id="h1"></div>

<h1>window.innerWidth + Height after setTimeout()</h1>
<div id="w2"></div>
<div id="h2"></div>

结果:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73493417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档