Home >Web Front-end >JS Tutorial >How to Restart CSS3 Animations Efficiently Without Using Timeouts?

How to Restart CSS3 Animations Efficiently Without Using Timeouts?

DDD
DDDOriginal
2024-11-10 18:35:03305browse

How to Restart CSS3 Animations Efficiently Without Using Timeouts?

Revisiting CSS3 Animation Restart: Unveiling an Alternative Approach

Restarting CSS3 animations can pose challenges, especially when attempting to restore an element's scale and animate it back to its original state. While removing and reinserting an element offers a workaround, it may not be the most efficient solution.

A more elegant approach involves leveraging reflow to apply changes without relying on timeouts. The following JavaScript function demonstrates this technique:

function reset_animation() {
  var el = document.getElementById('animated');
  el.style.animation = 'none';
  el.offsetHeight; /* trigger reflow */
  el.style.animation = null; 
}

In conjunction with the CSS and HTML below, this function allows for a seamless animation reset upon clicking:

#animated {
  position: absolute;
  top: 70px;
  width: 50px; height: 50px;
  background-color: black;
  animation: bounce 3s ease-in-out infinite;
}
@keyframes bounce {
  0% { left: 0; }
  50% { left: calc( 100% - 50px ); }
  100% { left: 0; }
}
<div>

By triggering a reflow, the animation is reset without the need for complex delays or timing. This approach provides a clean and efficient solution for restarting any CSS3 animation.

The above is the detailed content of How to Restart CSS3 Animations Efficiently Without Using Timeouts?. 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