繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM