检测何时使用JavaScript调整窗口大小?


125

当用户结束调整浏览器窗口大小时,jQuery或JavaScript有什么办法触发函数?

换句话说:

  1. 用户调整浏览器窗口大小时是否可以检测到鼠标向上移动事件?除此以外:
  2. 我可以检测到窗口调整大小操作何时完成吗?

我目前只能在用户开始使用jQuery调整窗口大小时触发事件


3
这里有一个jQuery和非jQuery解决方案:github.com/louisremi/jquery-smartresize
bradt 2012年

jquery-smartresize去抖动事件的漂亮解决方案!
tetri

@bradt可以使用香草JavaScript轻松完成所有操作时,就无需使用jQuery插件
James Douglas

Answers:


240

您可以使用.resize()每次实际改变宽度/高度时获取,如下所示:

$(window).resize(function() {
  //resize just happened, pixels changed
});

您可以在此处查看有效的演示,它会采用新的高度/宽度值并在页面中对其进行更新以供您查看。请记住,事件并没有真正开始结束,它只是在发生调整大小时“发生”……没有什么可说的。


编辑:通过评论看来,您想要的是“ on-end”事件,找到的解决方案可以做到这一点,但有一些例外(您无法以跨浏览器的方式区分鼠标向上和暂停,同为一个 Vs的停顿)。不过,您可以创建该事件,使其更加简洁,如下所示:

$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
    }, 500);
});

您可以在任何地方放置一个基本文件,然后执行任何操作……然后可以绑定到resizeEnd要触发的新事件,如下所示:

$(window).bind('resizeEnd', function() {
    //do something, window hasn't changed size in 500ms
});

你可以在这里看到这种方法的工作演示


1
这取决于浏览器,何时以及多少次触发调整大小事件:quirksmode.org/dom/events/resize.html
Chris Lercher 2010年

@chris_l:我不确定该页面的准确性如何……打开我在最新的Firefox中发布的演示,每次此处大小更改时都会触发该演示。我没有Opera进行测试,它可能仍然有所不同,但是它们至少比quirksmode建议的更加一致,我会给他们发送一条注释,这需要更新。
尼克·克拉弗

@Nick:是的,quirksmode页面仅覆盖FF直到3.1b2-但是这种显示取决于浏览器...
Chris Lercher 2010年

7
我只是想顺便说一句,当用户在移动设备上放大页面时也会触发此操作。
霍夫曼

4
window.addEventListener('resize',function(){},true);
WebWanderer

3

这可以通过在JavaScript中使用GlobalEventHandlers接口的onresize属性来实现,方法是将一个函数分配给onresize属性,如下所示:

window.onresize = functionRef;

以下代码段通过控制台在每次调整窗口大小时记录其innerWidth和innerHeight来演示此操作。(调整大小事件在窗口调整大小后触发)

function resize() {
  console.log("height: ", window.innerHeight, "px");
  console.log("width: ", window.innerWidth, "px");
}

window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>


3

仅使用JavaScript的另一种方法是:

window.addEventListener('resize', functionName);

每次更改大小都会触发此问题,就像其他答案一样。

functionName 是调整窗口大小时正在执行的函数的名称(不需要使用括号)。


0

如果您只想在滚动结束时检查,在Vanilla JS中,您可以提出这样的解决方案:

超级超级紧凑

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

所有3种可能的组合在一起(ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.