Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - How do I add a delay to preloader so the preloader will display even after page load for a couple of seconds

I am trying to add a delay to my preloader to give the page a cool effect. I would like to have the preloader display for a couple seconds even after the page has loaded. I have the preloader and it works fine I just need some help adding a delay to it.

here is my current code.

JS

window.addEventListener('load', () => {
        const preload = document.querySelector('.preload');
        preload.classList.add('preload-finish');
        
});`

CSS

    .preload    {
    position: fixed;
    top: 0;
    width: 100%;
    height: 100vh;
    background-color: #77b3d4;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: opacity 0.5s ease;
}

.preload h3 {
    position: absolute;
    top: 75%;
    transform: translateY(-75%);
    color: white;
    font-size: 40px;
    font-family: sans-serif;
}

.preload-finish {
    opacity: 0;
    pointer-events: none;
}
question from:https://stackoverflow.com/questions/65857290/how-do-i-add-a-delay-to-preloader-so-the-preloader-will-display-even-after-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can also use the setTimeout() javascript function:

window.addEventListener('load', () => {
        const preload = document.querySelector('.preload');
        setTimeout( function() {
            preload.classList.add('preload-finish');
        }, 1000 );
});

Change the 1000 at the end to whatever number you like to set the delay in milliseconds. Here is a tutorial by w3schools https://www.w3schools.com/jsref/met_win_settimeout.asp


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...