[英]window resize event continually fires in ie7
舊標題:javascript中的窗口調整大小事件的setTimeout節流在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元素會被預先添加到頁面上的ul元素,然后計數器會遞增。 而已。
這表明問題在於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();
};
另一種解決方案是檢查調整大小處理程序以查看窗口的寬度是否已更改。 這樣,您可以忽略不是由調整大小的窗口引起的調整大小事件。 另請參閱: Internet Explorer中的window.resize事件觸發
嘗試這樣的事情:
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.