iOS上的Google 104在我旋转我的设备后报告了不正确的window.innerWidth
和window.innerHeight
值。例如:
在纵向模式下加载我的页面,414 x 714
.
390 x 334
我在下面创建了一个代码片段来测试。在出现错误的值之前,可能需要三次尝试:
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);
body{font-family: sans-serif}
h1{font-size: 16px}
div{
font-size: 16px;
height: 20px;
background: #eee;
margin-bottom: 2px;
}
<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中。有谁知道这种行为的来源,或者解决这个错误的方法吗?
发布于 2022-08-25 20:55:57
这绝对是一个缺陷,只有谷歌Chrome在iOS。解决方案是在读取setTimeout和window.innerHeight
值之前添加一个简短的window.innerHeight
()。
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();
body{font-family: sans-serif}
h1{font-size: 16px}
div{
font-size: 16px;
height: 20px;
background: #eee;
margin-bottom: 2px;
}
<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>
结果:
https://stackoverflow.com/questions/73493417
复制相似问题