2012-09-11 29 views
4

老題目:窗口的setTimeout油門調整事件中的JavaScript在IE7不斷激發窗口調整大小事件不斷激發在IE7

我有以下腳本

jQuery(document).ready(function(){ 
    throttleTest(); 
}); 

function throttleTest() { 

    var throttleTimer, 
     testCount = 1; 

    jQuery(window).on({ 
     "resize": function(){ 
      clearTimeout(throttleTimer); 
      throttleTimer = setTimeout(function() { 
       jQuery("ul.testList").prepend("<li>Prepended list item number: " + testCount + "</li>"); 
       testCount++; 
      }, 500);   
     } 
    }); 

}; 

而以下HTML

<ul class="testList"> 
</ul> 

使用setTimeout節流技術,只要用戶停止調整瀏覽器500ms的大小,它應該只將一個列表項添加到testList ul中。基本上它只在瀏覽器的每次調整大小時運行一次setTimeout代碼,這是由於在設置clearTimeout之前。這種技術只允許在需要時觸發代碼,而不是在每次調整大小事件時觸發代碼,無論用戶何時調整瀏覽器大小,代碼可能會發生幾十次。

這適用於除ie7以外的所有瀏覽器。在ie7中奇怪的是,代碼繼續運行,並停止停止預先列表項到ul。

我已成立了一個演示這裏:http://jsfiddle.net/cQRjp/

採取IE7一看,你會看到這個問題。 有沒有人知道爲什麼這是ie7失敗?

編輯號:1:

我已經剝離下來的代碼,以便在窗口上調整的li元素被前置到頁面上的UI元素,然後計數器遞增。而已。

這表明問題在於ie7如何解釋調整大小事件,與節流計時器無關。似乎預先將一個li項添加到頁面中會觸發ie7中的resize事件,因此,調整大小會不斷被觸發。我在這裏設置了一個新的演示:http://jsfiddle.net/gnKsE/警告這個鏈接會使你的ie7瀏覽器崩潰。

我能想到的這個問題的一個解決方案是在觸發後立即關閉resize事件,然後在我運行其中的代碼後再次將其設置爲備份。像這樣:

jQuery(document).ready(function(){ 
    functionName(); 
}); 

function functionName() { 

    var throttleTimer, 
     testCount = 1; 


    function turnOnResize() { 
     jQuery(window).on({ 
      "resize.anyname": function(){ 
       jQuery(window).off(".anyname"); 
       jQuery("ul.testList").prepend("<li>Resize event: " + testCount + "</li>"); 
       testCount++; 
       setTimeout(function() { 
        turnOnResize(); 
       }, 50); 
      } 
     }); 
    } 
    turnOnResize(); 

}; 

回答

1

另一個解決辦法是讓你調整大小處理程序檢查,看看是否窗口的寬度發生了變化。這樣,您可以忽略不是由被調整大小的窗口造成的調整大小事件。另請參見:window.resize event firing in Internet Explorer

嘗試這樣:

jQuery(document).ready(function($){ 
    var lastWindowHeight = window.innerHeight, // Could use $(window).height() but $(window) is expensive 
     lastWindowWidth = window.innerWidth, 
     testCount = 1; 

    // Handles all resize events (which for IE7 includes when _anything_ in the DOM is resized) 
    function resizeHandler() { 
     if (lastWindowHeight !== window.innerHeight || lastWindowWidth !== window.innerWidth) 
      windowResizeHandler.apply(this, arguments); 
    } 

    // Handles resize events that result from the window changing size 
    function windowResizeHandler() { 
     lastWindowHeight = window.innerHeight; 
     lastWindowWidth = window.innerWidth; 
     $("ul.testList").prepend("<li>Resize event: " + testCount + "</li>"); 
     testCount++; 
    } 

    $(window).on("resize", resizeHandler); 
}); 
+0

順便說一句,您可能需要使用類似:document.documentElement.clientWidth得到寬度在IE7中,如果你不使用jQuery來做到這一點。 – iX3