Home >Web Front-end >CSS Tutorial >How Can I Precisely Control CSS3 Animation Completion and Remove an Element After the Final Frame?

How Can I Precisely Control CSS3 Animation Completion and Remove an Element After the Final Frame?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 20:28:11563browse

How Can I Precisely Control CSS3 Animation Completion and Remove an Element After the Final Frame?

Controlling CSS3 Animation Completion

In the realm of web development, CSS3 animations have become a powerful tool for enhancing user experience. Однако, when designing animations that require precise control over their end states, stopping them on their last frame can pose a challenge.

This article addresses such a scenario, where a multi-part CSS3 animation plays on click, with the final part intended to remove a div from the screen. Unfortunately, the animation continuously reverts to its original state. To resolve this issue, we explore two solutions:

1. Freezing the Animation on the Last Frame:

To freeze the animation on its last frame (100% completion), we employ the CSS property animation-fill-mode: forwards;. This directive instructs the browser to maintain the final animation state even after the animation has ended.

2. Removing the Div after the Animation:

Alternatively, if removing the div entirely is desired, we can use JavaScript to remove the element from the DOM after the animation has played. This can be achieved with the following sequence:

document.getElementById("myDiv").addEventListener("animationend", function() {
  this.parentNode.removeChild(this);
});

As the animation completes, the "animationend" event is triggered, causing the div to be removed from the page.

Example:

@keyframes colorchange {
  0%   { transform: scale(1.0) rotate(0deg); }
  50%  { transform: rotate(340deg) translate(-300px,0px) }
  100% { transform: scale(0.5) rotate(5deg) translate(1140px,-137px); }
}

#myDiv {
  animation: colorchange 1s infinite;
  animation-fill-mode: forwards;
}

In this example, the div with ID "myDiv" undergoes an animation that finishes with a scale and rotation transformation. By setting "animation-fill-mode: forwards;", the final state is preserved after the animation ends.

The above is the detailed content of How Can I Precisely Control CSS3 Animation Completion and Remove an Element After the Final Frame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn