旧标题: 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);
}
});
};和下面的
<ul class="testList">
</ul>使用setTimeout节流技术,它只应在用户停止调整浏览器大小500 it时将列表项添加到testList ul。基本上,它只在浏览器的每一个调整大小上运行一次setTimeout代码,这是因为在设置clearTimeout之前。这种技术只允许在需要时触发代码,而不是在每个调整大小的事件上触发,每当用户调整浏览器大小时,会触发数十次。
这适用于所有浏览器,但ie7除外。奇怪的是,在ie7中,代码继续运行,并停止将列表项放在ul之前。
我在这里设置了一个演示:http://jsfiddle.net/cQRjp/
在ie7中查看一下,您将看到问题所在。,有人知道为什么ie7?失败了吗?
编辑编号:1:
我已经简化了代码,以便在窗口上调整安莉元素的大小,使其在页面上被添加到ul元素中,然后增加一个计数器。就这样。
这表明问题在于ie7如何解释调整大小事件,而与节流阀计时器无关。在ie7中,将安莉项放在页面前似乎会触发调整大小事件,因此会连续触发调整大小。我在这里设置了一个新的演示: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();
};发布于 2012-12-17 17:07:48
另一种解决方案是让您的调整处理程序检查窗口的宽度是否已经改变。这样,您就可以忽略被调整大小的窗口所导致的调整大小的事件。另见: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);
});https://stackoverflow.com/questions/12366315
复制相似问题