gpt4 book ai didi

javascript - 窗口调整大小事件在 ie7 中不断触发

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:35:31 25 4
gpt4 key购买 nike

旧标题:javascript 中窗口调整大小事件的 setTimeout throttle 在 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 throttle 技术,它应该只在用户停止调整浏览器大小 500 毫秒后将列表项添加到 testList ul。基本上它只在每次调整浏览器大小时运行一次 setTimeout 代码,因为在设置之前有 clearTimeout。这种技术允许仅在需要时触发代码,而不是在每次调整大小事件时触发,每当用户调整浏览器大小时,这可能会发生数十次。

这适用于除 ie7 之外的所有浏览器。奇怪的是,在 ie7 中,代码继续运行并停止停止将列表项添加到 ul。

我在这里设置了一个演示:http://jsfiddle.net/cQRjp/

在 ie7 中查看,您将看到问题所在。 有谁知道为什么这在 ie7 中失败了?

编辑编号:1:

我已经精简了代码,以便在调整窗口大小时将 li 元素添加到页面上的 ul 元素之前,然后递增一个计数器。就是这样。

这表明问题在于 ie7 如何解释调整大小事件,与 throttle 计时器无关。似乎在页面前添加一个 li 项目会触发 ie7 中的调整大小事件,因此,会不断触发调整大小。我在这里设置了一个新的演示:http://jsfiddle.net/gnKsE/ 警告此链接会使您的 ie7 浏览器崩溃。

对于这个问题,我能想到的一个解决方案是在触发调整大小事件后立即将其关闭,然后在我运行其中的代码后重新设置它。像这样:

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

};

最佳答案

另一种解决方案是让调整大小处理程序检查窗口的宽度是否已更改。这样您就可以忽略不是由调整窗口大小引起的调整大小事件。另请参阅: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);
});

关于javascript - 窗口调整大小事件在 ie7 中不断触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12366315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com