window.onload未在IE中启动

window.onload is not firing in IE

本文关键字:启动 IE 未在 onload window      更新时间:2023-12-13

这是我的代码:

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中启动(控制台没有记录任何内容)-有什么想法吗?提前感谢!

您可以使用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)
        }
    }
}

如注释中所述,您的函数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)
        }
    }
}