简体   繁体   中英

How can I create a CSS animation in JavaScript?

How can I create the CSS animation below in JavaScript? I've looked all over Google, and tried multiple times to create this but I couldn't figure out how to do this.

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 100;
  }
}

To run this, I know I can use what is shown below, but I don't know how to create this animation. Can anyone help?

element.style.animation = "fadeIn 5s linear";

You can use javascript with transition to achieve it

 // start frame const start = { opacity: 0 }; // end frame const end = { opacity: 1 }; const element = document.querySelector('span'); Object.assign(element.style, start); element.style.transition = 'all 5s linear'; requestAnimationFrame(() => { Object.assign(element.style, end); });
 <span>Lorem Ipsum</span>

What do you mean exactly with "Create in Javascript"? Without using CSS?

If so, you can use a simple interval to update the opacity of the element until it reached 0 or 100. Simple example:

let opacity = 0; 
const fadeEl = document.getElementById("fadeInElementIdWithOpacity0");

    const fadeInInterval = setInterval(() => { 
         
        if (opacity < 1) { 
            opacity = opacity + 0.1 
            fadeEl.style.opacity = opacity; 
        } else { 
            clearInterval(fadeInInterval); 
        } 
    }, 200);

You can first define this function with whatever amount of intervals that you want and then call it with any querySelector

function fadeIn(x) { 
            var fade = document.querySelector(x); 
            var opacity = 0; 
            var intervalID = setInterval(function() { 
  
                if (opacity < 1) { 
                    opacity = opacity + 0.1 
                    fade.style.opacity = opacity; 
                } else { 
                    clearInterval(intervalID); 
                } 
            }, 200); 
        } 

havnig this function in console and running fadeIn(".-logo") will fade in the stackoverflow's logo

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