JavaScript/JQuery: $(window).resize 调整大小完成后如何触发?

2022-01-30 00:00:00 jquery javascript

我正在使用 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.

相关文章