Javascript Div显示至少1s,或直到加载主要内容-以先到者为准

Javascript Div显示至少1s,或直到加载主要内容-以先到者为准,javascript,jquery,Javascript,Jquery,我已经实现了下面的脚本,以确保预装页面显示在我的网站主页上,直到主页内容完全加载 我想调整以下内容,以确保预加载程序始终显示最短的时间(即1s),以确保它始终显示,即使在快速连接时也是如此。预加载程序应至少显示1s,或直到加载主要内容(以先到者为准)。这可能吗 HTML <div class='preloader'> <div class="preloader-logo">Logo</div> <div class="preloader-

我已经实现了下面的脚本,以确保预装页面显示在我的网站主页上,直到主页内容完全加载

我想调整以下内容,以确保预加载程序始终显示最短的时间(即1s),以确保它始终显示,即使在快速连接时也是如此。预加载程序应至少显示1s,或直到加载主要内容(以先到者为准)。这可能吗

HTML

<div class='preloader'>
    <div class="preloader-logo">Logo</div>
    <div class="preloader-loading-icon">Loading</div>
</div>

<main>Content goes here, should be hidden initially until fully loaded (or 1s have lapsed).</main>
CSS

/* Preloader Splash */
$(window).load(function(){
    $('main').animate({opacity: 1},300);
    $('.preloader').fadeOut(500);
});
.preloader {
    display: block;
    position: fixed;
    width: 100%;
    height: 100%;
    overflow: hidden;
    top: 0;
    left: 0;
    z-index: 9999;
    background: rgba(255,102,51,1);
}

.preloader-logo {
    background: url(images/ui-sprite.svg) no-repeat 0 -300px;
    position: absolute;
    width: 140px;
    height: 58px;
    top: 50%;
    left: 50%;
    text-indent: -9999px;
}

.preloader-loading-icon {
    background: url(images/preloader-loading.svg) no-repeat 50%;
    text-indent: -9999px;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: 90px;
    width: 40px;
    height: 40px;
}

我不确定我是否喜欢这一点,但这是实现您所期望的目标的一种简单方法:

var timedOut = false;
var loaded = false;

/* Preloader Splash */
$(window).load(function(){
    loaded = true;
    hideLoading();
});

setTimeout(function(){
    timedOut = true;
    hideLoading();
}, 1000);

function hideLoading(){
    if(loaded && timedOut){
        $('#container').animate({opacity: 1},300);
        $('.preloader').fadeOut(500);
    }
}
这意味着加载仅在1s已通过时隐藏加载,而在页面已加载时1s将关闭加载

原始答复:

页面加载完成后,您可以将其显示1s:

/* Preloader Splash */
$(window).load(function(){
    setTimeout(function(){
        $('#container').animate({opacity: 1},300);
        $('.preloader').fadeOut(500);
    , 1000);
});

可能有更好的方法,因为这意味着即使在加载速度较慢的页面上,也会在加载完成后1s,而不是立即加载。因此,加载时间+1s,而不是加载时间或1s

最初,您的主要内容
#容器
不透明度应设置为
0
,以便动画可以显示任何效果

$(window).load(function(){
    // Code here executes when the whole content (with images etc) is loaded
});

什么是
#容器
?如何检查是否加载了所有内容?您正在寻找一个去盎司功能。这篇文章可能很有用,你可以使用佩斯,避免自己重新发明轮子@抱歉,这是个错误,我已经更新了问题我不认为这很有用,最好检查一个真正的加载状态,这可能会对慢加载后的等待1s进行排序,但我只是建议他可以这样做,检查加载状态,就像问题中的一样函数是setTimeout no setTimeoufThanks@Dhunt,这是一个有用的解决方案,但无论持续时间如何,每次加载都会增加1的风险是我宁愿避免的!