简体   繁体   中英

How do I get Javascript to run animation instead of CSS

I am doing a splash screen for my website. I have managed to get it working as JS wasn't working.

"use strict";

$(function(){
    $('.fadein img:gt(0)').hide();
    setInterval(function(){
      $('.fadein :first-child').fadeOut()
         .next('img').fadeIn()
         .end().appendTo('.fadein');}, 
     6000);
});


const splash = document.querySelector('.splash');

document.addEventListener('DOMContentLoaded', (e)=> {
    setTimeout(function()=> {
        splash.classList.add('display-none');
    }, 10000);
})

The bottom code breaks the top code (which works and runs the slideshow).

.splash {
    position: fixed;
    top: 0;
    left: 0;
    width: auto;
    height: auto;
    z-index: 200;
}

.splash.display-none {
    position: fixed;
    opacity: 0; 
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: -10;
    transition: all 6s;
}

@keyframes fadeIn {
    to{
        opacity: 0;
        visibility: hidden;
    }
}

@-webkit-keyframes fadeIn {
    to{
        opacity: 0;
        visibility: hidden;
    }
}

.splash {
    opacity: 1;
    animation: fadeIn 2s ease-in forwards;
    -webkit-animation: fadeIn 2s ease-in forwards;
    animation-delay: 0.75s;
}

.fade-in {
    height: 100vh;
    width: 100%;
}

This is my CSS, and the animation works. My only problem with it is that if I went back to homepage, the animation would happen again. This is why I want to use Javascript so it only happens on a new instance of loading the website.

Use localStorage to see if splash screen has been shown already. Set them to display:none immediately so they are completely hidden. I'm not sure what you actually want to happen with the splash, so I'm just hiding them completely. I think it would be more pleasant to just have a very short opacity transition instead.

You can use localStorage.removeItem to clear the splashed flag.

You may want to use a unique ID for the localStorage name for this specific splash, and not just "splashed".

document.addEventListener('DOMContentLoaded', (e)=> {
    const splashed = localStorage.getItem('splashed')
    const splash = document.querySelector('.splash');
    const splasher = () => {
        splash.classList.add('display-none');
        localStorage.setItem('splashed',1)
    };
    splashed ? splash.forEach(x=>x.style.display='none') : setTimeout(splasher, 10000);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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