jQuery 中的 window.resize 多次触发

新手上路,请多包涵

我在 HTML 文件中有以下 JavaScript/jQuery 代码:

 <html>
  <head>
    <script src="http://code.jquery.com/jquery-1.6.2.min.js"
     type="text/javascript"></script>
    <script language="javascript">
    $(window).resize(function(){alert('hi');});</script>
  </head>
  <body>
    resize me
  </body>
</html>

它看起来相对简单,但是当我调整浏览器窗口大小时,我在 Chrome 和 IE9 上得到两个连续的警告窗口,而且我似乎使 Firefox5 崩溃了。

我错过了什么?每个维度 (x/y) 是一场火灾吗?

原文由 Matt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

你明白了,有些浏览器会在调整大小开始时触发并在结束时再次触发,而其他浏览器(如 FF)会连续触发。解决方案是使用 setTimeout 来避免一直开火。可以 在此处 找到示例。这是来自同一参考的代码:

 (function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
    // smartresize
    jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');

// usage:
$(window).smartresize(function(){
  // code that takes it easy...
});

原文由 Radu 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个简单的示例,如果用户停止调整大小 500 毫秒(半秒),您的函数就会触发。 clearTimeout 会阻止您的函数不断重新启动。您可以根据需要调整此值。 500 毫秒可能太快了,你可能会把它提高到 1000,这取决于你在函数内部做了什么

var resizeTimeout;
$(window).resize(function(){
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(function(){
        alert('your function to run on resize');
    }, 500);
});

原文由 dave.mcalpine 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题