Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - window.resize in jquery firing multiple times

I have the following javascript/jquery code in an HTML file:

<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>

It appears relatively straight forward, however when I re size the browser window, I get two successive alert windows on Chrome and IE9 and I seemingly crash FF5.

What am I missing? Is it one fire per dimension (x/y)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You got it, some browsers fire on resize start and again on end while others like FF fire continuously. Solution is to use setTimeout to avoid firing all the time. An example can be found here. Here is the code from the same reference:

(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...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...