Home >Web Front-end >CSS Tutorial >How Can I Pause and Resume CSS3 Animations Using Only JavaScript?
Pause and Resume CSS3 Animation with JavaScript
Problem:
How to pause and resume a CSS3 animation using JavaScript without relying on external libraries?
Solution:
Define the animation using CSS keyframes, specifying the opacity values and timing for each step.
Create JavaScript functions to handle pausing and resuming the animation:
const pauseAnimation = (element) => { element.style.animationPlayState = "paused"; }; const resumeAnimation = (element) => { element.style.animationPlayState = "running"; };
Add event listeners to the animated elements to trigger the pause and resume actions:
document.getElementById("pic1").addEventListener("click", () => { pauseAnimation(document.getElementById("pic1")); }); document.getElementById("pic2").addEventListener("click", () => { resumeAnimation(document.getElementById("pic2")); });
Additional Notes:
.paused{ -webkit-animation-play-state:paused; -moz-animation-play-state:paused; -o-animation-play-state:paused; animation-play-state:paused; }
const pauseAnimation = (element) => { element.classList.add("paused"); }; const resumeAnimation = (element) => { element.classList.remove("paused"); };
This allows you to pause and resume the animation by simply toggling this CSS class without the need for event listeners.
The above is the detailed content of How Can I Pause and Resume CSS3 Animations Using Only JavaScript?. For more information, please follow other related articles on the PHP Chinese website!