2011-10-15 95 views
0

我使用Paul Irish Smartresize,但當調整窗口大小時,resize()中的函數會多次觸發,導致手風琴無法正常工作。 有沒有人知道爲什麼會發生這種情況? 下面是代碼運行:http://jsfiddle.net/rebel2000/PnAH7/6/當在jQuery中調整大小()時,觸發多次觸發

  $(document).ready(function(){ 


      (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'); 

      function anim3() { 
       $('#button').click(
        function(){ 
         if($(this).hasClass('active')){ 
          $(this).animate({ "height": "30px"}, { queue:true, duration: 900 }); 
          $(this).removeClass('active'); 
          return false; 
         } else {     

          $(this).animate({ "height": "100px"}, { queue:true, duration: 900 }); 
          $(this).addClass('active'); 
          return false; 
         } 
        } 
       );      
      } 
     //anim3(); 
     $(window).smartresize(function(){ 
      anim3(); 
     }); 

      }); 
+0

小提琴的代碼不同於問題的代碼。 –

+0

對不起,我更新了代碼! – Nikos

回答

2

這是因爲,當你調整大小,調整大小事件觸發多次。如果JavaScript循環通過驗證窗口大小的檢測,它會檢測到它比以前更小/更大,然後再次觸發它。由於循環速度非常快,在您的「單個」重新調整大小期間,您會發生多次火災。

你可以做這樣的事情:

var idCounter = 0; 
$(window).smartresize(function(){ 
    var myId=(++idCounter); 
    setTimeout(function(){ 
    if(myId===idCounter){ 
     anim3(); 
    } 
    }, 500); // 500 milli the user most likely wont even notice it 
} 

這應該忽略對最後一個火災多,只有過程。 (除非你把大量的時間來調整,在這種情況下,你可以增加超時)

+0

感謝代碼,它的工作原理很好,但我意識到我有另一個問題...如果我調整窗口只有一次然後代碼是好的,但是當我調整窗口多次,然後函數被調用幾次。你有什麼想法嗎?你可以在下面的鏈接http://jsfiddle.net/rebel2000/PnAH7/6/ – Nikos

+1

中看到它的行動。我終於搞定了,我需要一個標誌來讓我的函數只運行一次。 http://jsfiddle.net/rebel2000/jwyeC/ – Nikos

相關問題