我需要使用window.resize
事件,但我注意到,在移动设备上,即使显示键盘(例如当聚焦搜索字段时),它也会被触发.对我来说,这不是一件好事.a js还是css是避免它的方法?禁用它还是检测事件的"虚假"?
我需要使用window.resize
事件,但我注意到,在移动设备上,即使显示键盘(例如当聚焦搜索字段时),它也会被触发.对我来说,这不是一件好事.a js还是css是避免它的方法?禁用它还是检测事件的"虚假"?
这是检测宽度/高度变化的基本示例.要在SO.com上通过触发可靠的resize
事件进行测试,请单击Expand snippet链接,然后单击Run,或者单击Run,然后单击Full page链接.要模拟键盘打开,您可以打开开发工具并将其固定到浏览器窗口的底部,然后打开/关闭它以查看仅高度发生变化.
有关检测设备方向变化的示例,请参阅Detect rotation of Android phone in the browser with JavaScript,因为它比监听resize
事件并再次读取当前高度/宽度更复杂.例如,在Firefox开发工具中,在模拟设备上使用旋转按钮时甚至没有触发resize
.
let width = window.innerWidth;
let height = window.innerHeight;
let statusElement = document.querySelector('p.status');
let heightElement = document.querySelector('p.height');
let widthElement = document.querySelector('p.width');
widthElement.innerText = width;
heightElement.innerText = height;
addEventListener("resize", (event) => {
let newWidth = window.innerWidth;
let newHeight = window.innerHeight;
widthElement.innerText = newWidth;
heightElement.innerText = newHeight;
if (newWidth !== width && newHeight !== height) {
// decide if you want to handle this here and/or in a separate orientationchange event listener
statusElement.innerText = 'both changed, decide what you want to do';
} else if (newWidth !== width) {
statusElement.innerText = 'only width changed, react to this';
} else if (newHeight !== height) {
statusElement.innerText = 'only height changed, probably ignore this';
} else {
// ignore the resize event if the height/width didn't actually change
}
width = newWidth;
height = newHeight;
});
<p class="status">Window loaded</p>
<p class="height"></p>
<p class="width"></p>