JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?(JavaScript/JQuery: $(window).resize 调整大小完成后如何触发?)
问题描述
我正在使用 JQuery:
I'm using JQuery as such:
$(window).resize(function() { ... });
但是,如果用户通过拖动窗口边缘以使其变大/变小来手动调整浏览器窗口的大小,则上述 .resize
事件会触发多次.
However, it appears that if the person manually resizes their browser windows by dragging the window edge to make it larger/smaller, the .resize
event above fires multiple times.
问题:如何在浏览器窗口大小调整完成后调用函数(以便事件只触发一次)?
Question: How to I call a function AFTER the browser window resize completed (so that the event only fires once)?
推荐答案
这里是CMS的解决方案的修改,可以在你的代码中的多个地方调用:
Here's a modification of CMS's solution that can be called in multiple places in your code:
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
用法:
$(window).resize(function () {
waitForFinalEvent(function(){
alert('Resize...');
//...
}, 500, "some unique string");
});
如果您只调用一次,CMS 的解决方案很好,但如果您多次调用它,例如如果您的代码的不同部分设置单独的回调来调整窗口大小,那么它将失败 b/c 他们共享 timer
变量.
CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer
variable.
通过此修改,您可以为每个回调提供一个唯一 ID,这些唯一 ID 用于将所有超时事件分开.
With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.
这篇关于JavaScript/JQuery: $(window).resize 调整大小完成后如何触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript/JQuery: $(window).resize 调整大小完成后如何触发?
基础教程推荐
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01