window.onload没有在IE中触发

时间:2013-11-28 07:06:50

标签: javascript jquery dom

这是我的代码:

var scrollOnLoad = function scrollOnLoad(selector, offset) {
    window.onload = function() {
        if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}

以下是它的表现方式:

scrollOnLoad(".content-wrapper", 50);

我注意到window.onload事件没有在IE中触发(控制台没有记录任何东西) - 任何想法为什么?提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用document.readyState属性:

function scrollOnLoad(selector, offset) {
    if(document.readyState === 'complete')
        x();
    else
        document.addEventListener('readystatechange', function(){
            if(document.readyState === 'complete')
                x();
        });

    function x(){
        if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}

答案 1 :(得分:0)

如评论中所述,您的函数scrollOnLoad将在窗口加载后执行。

现在,在更好的情况下,应在全球范围内添加这些事件。

所以它应该像

 window.onload = function() {
  if(someConditionIsSatisfied){

    if ($(window).height() <= 800) {
            var attempts = 100;
            var interval = setInterval(function() {
                var h = $(selector).height();
                console.log("attempt #" + attempts + ", h=" + h);
                if (h > 0 || !attempts--) {
                    $("body,html").animate({scrollTop : h + offset}, '1000');
                    clearInterval(interval);
                }
            }, 50)
        }
    }
}