使用jQuery获取调整大小时的尺寸变化

4

我在我的网站中使用了以下代码:

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

很遗憾,使用移动设备访问该网站时会发生微小的大小重置事件。我想增加一个公差,以使这些微小变化不会触发重新加载。为此,我需要知道重置事件中发生的尺寸变化。我一直在研究event对象,但它太庞大且难以理解。

提前感谢您的帮助 :)


你所需要做的就是使用媒体查询。 - Jack Bashford
这并不能解决问题的根本原因。@JBDouble05 请仔细阅读问题。 - Worm
1
但我的意思是,你应该只使用媒体查询,这样如果你在移动设备上,你的函数就不会发生。这是我的第一个想法。 - Jack Bashford
1
@JBDouble05,肯定会导致窗口大小调整。 - user2575725
非常好的观点 @Arvind - Worm
显示剩余2条评论
2个回答

2

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

以下是如何在宽度发生一定总量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();
  }

})

这样做不行,因为var width = $(window).width();这一行代码获取的是新的宽度,所以你在将新的宽度与新的宽度进行比较。我需要想办法获取旧的宽度。 - Worm
嗨@Worm,它只在第一次调整大小事件中执行。注意window.startWidth只被存储一次,然后被重复使用作为参考宽度来检测阈值?或者我在这里漏掉了什么? - Dacre Denny

0

JBDouble05的有益评论和Dacre Denny的有益答案的基础上,我制定了一个最终解决方案,以满足我的需求。希望这里能帮助未来的他人。

var OGwidth = $(window).width();
var OGheight = $(window).height();
var threshold = 50;
$(window).resize(function (e) {
    if (OGwidth < 768) {
        var newWidth = $(window).width();
        var newHeight = $(window).height();

        var widthChange = Math.abs(OGwidth - newWidth);
        var heightChange = Math.abs(OGheight - newHeight);

        if (widthChange > threshold || widthChange > threshold) {
            window.location.reload();
        }

    } else {
        window.location.reload();
    }
    //reset for next resize
    OGwidth = newWidth;
    OGheight = newHeight;
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接