使用 jQuery 在调整大小时获取维度的更改



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

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

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

提前致谢:)

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

下面显示了如果宽度更改了某个总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();
}
})

基于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;
})

最新更新