如何避免在移动设备中收到虚假的调整大小事件?

问题描述 投票:0回答:1

我需要使用

window.resize
事件,但我注意到在移动设备上,即使显示键盘(例如,聚焦搜索字段时)也会触发该事件。就我而言,这不是一件好事。 js 或 css 是否可以避免这种情况?禁用它或检测事件的“虚假性”?

javascript css dom-events
1个回答
0
投票

这是检测宽度/高度变化的基本示例。要在 SO.com 上测试此功能,请单击 Full page 链接,否则

resize
事件似乎无法可靠触发。

请参阅 使用 JavaScript 在浏览器中检测 Android 手机的旋转,了解检测设备方向变化的示例,因为它比侦听

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>

© www.soinside.com 2019 - 2024. All rights reserved.