2011-07-12 147 views
11

我有一個HTML文件,下面的JavaScript/jQuery代碼:window.resize 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上的警告窗口和我看起來崩潰FF5。

我錯過了什麼?它是每個維度(x/y)的一個火嗎?

+1

當你拖動調整大小時,它會觸發很多次。 –

+0

是的,我只是單擊窗口句柄中的最大恢復按鈕。它在那時也發射了兩次。 – Matt

+0

如果你想避免這個,看看這個插件:http://benalman.com/projects/jquery-throttle-debounce-plugin/ –

回答

25

你明白了,有些瀏覽器在調整開始時重新開始調整大小,而另一些則像FF一樣持續着火。解決方法是使用setTimeout以避免始終觸發。一個例子可以發現here。下面是來自相同參考的代碼:

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

感謝這個答案幫助解決我的問題:http://stackoverflow.com/問題/ 13710834/problems-with-mobiscroll-orientationchange-and-access-address-bar-crashes-some/13767875#13767875 – Soenhay

+0

我們如何解除這個事件? – Ninjaneer

4

似乎是這樣的瀏覽器特有的怪癖。據爲resize事件的文檔:在resize處理

代碼不應該依賴於次 處理程序被調用的數量。根據實施情況,調整大小事件可能是 ,因爲調整大小時(IE瀏覽器和基於WebKit的瀏覽器(例如Safari和Chrome)中的典型行爲 ),或者只在調整大小操作結束時發生一次在其他一些瀏覽器(如Opera)中的典型 行爲)。

(重點煤礦)

一種解決方法是設置一個計時器,並檢查是否窗口的尺寸發生改變。

7

這裏有一個簡單的例子,如果用戶停止調整大小爲500毫秒(半秒鐘),你的功能將閃光。 clearTimeout可以防止你的函數不斷被重寫。您可以根據需要調整此值。 500毫秒可能太快,你可能會碰到1000,取決於你在做什麼功能

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