简体   繁体   English

在IE中未触发window.onload

[英]window.onload is not firing in IE

Here is my code: 这是我的代码:

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)
        }
    }
}

and here is how its caling: 这是它的标定方式:

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

I've noticed that window.onload event is not firing in IE (console is not logging anything) - any ideas why? 我注意到window.onload事件未在IE中触发(控制台未记录任何内容)-为什么有任何想法? Thanks in advance! 提前致谢!

You can use document.readyState property: 您可以使用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)
        }
    }
}

As mentioned in comments your function scrollOnLoad is getting executed after the window has loaded. 如注释中所述,在窗口加载后,您的功能scrollOnLoad将被执行。

Now in better scenarios these events should be added in global scope. 现在,在更好的情况下,应将这些事件添加到全局范围内。

So it should be like 所以应该像

 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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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