首页 > 解决方案 > 使用 jQuery 获取调整大小时的尺寸变化

问题描述

对于我的网站,我使用以下代码:

$(window).resize(function (event) {
    window.location.reload();
});

不幸的是,在移动设备上使用该网站时,会发生微小的调整大小事件。我想设置一个容差,以便这些微小的更改不会触发此重新加载。为此,我需要知道在调整大小事件中发生的尺寸变化。我一直在看这个event物体​​,但它又大又丑。

提前致谢 :)

标签: javascriptjqueryhtml

解决方案


您可以通过跟踪原始窗口尺寸,然后将这些尺寸与当前尺寸(在每次调整大小事件期间获取)进行比较以确定变化量来实现这一点。

下面显示了如果宽度改变了一定的总量,你如何触发重新加载THRESHOLD

var THRESHOLD = 50; // the threshold that must be exceeded to trigger reload

$(window).resize(function(e) {

  var width = $(window).width();

  // Record the starting window width that the comparison will
  // be relative to
  if(window.startWidth == undefined) {
    window.startWidth = width;
  }

  // Calculate the total change since first resize event
  var widthChange = Math.abs(width - window.startWidth);

  // If change exceeds THRESHOLD, trigger reload
  if(widthChange > THRESHOLD) {
    window.location.reload();
  }

})

推荐阅读