我需要使用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>

Javascript相关问答推荐

如何使用CSS和JavaScript创建粘性、凝聚力的形状到形状(容器)变形?

我的YouTube视频没有以html形式显示,以获取免费加密信号

如何在不分配整个数组的情况下修改包含数组的行为主体?

*ngFor和@代表输入decorator 和选角闭合

Google Apps脚本中的discord邀请API响应的日期解析问题

无法在nextjs应用程序中通过id从mongoDB删除'

Phaser 3 console. log()特定游戏角色的瓷砖属性

为什么这个JS模块在TypeScript中使用默认属性导入?""

Angular material 拖放堆叠的牌副,悬停时自动展开&

如何在ASP.NET JavaScript中使用Google Charts API仅对绘制为负方向的条形图移动堆叠条形图标签位置

类构造函数不能在没有用With Router包装的情况下调用

扩展类型的联合被解析为基类型

expo 联系人:如果联系人的状态被拒绝,则请求访问联系人的权限

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

如何找到带有特定文本和测试ID的div?

更新文本区域行号

React数组查找不读取变量

Firebase函数中的FireStore WHERE子句无法执行

在每次重新加载页面时更改指针光标