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

时间:2015-10-29 13:13:06

标签: javascript jquery

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

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

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>

JS

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

CSS

.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;
}

2 个答案:

答案 0 :(得分:1)

不确定我喜欢这个,但它是实现您所寻找目标的简单方法:

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将关闭加载。

原始答案:

您可以在页面加载完成后显示1秒:

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

可能有更好的方法,因为这意味着即使在慢速加载页面上,它也会在完成加载后1秒而不是直接离开。所以加载时间+ 1s而不是加载时间或1s

答案 1 :(得分:0)

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

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