La forma más común y directa de pausar y reanudar una animación CSS es manipulando la propiedad CSS animation-play-state del elemento animado. Esta propiedad acepta principalmente dos valores:
running: La animación se está ejecutando. Este es el valor por defecto.paused: La animación se detiene en el fotograma en el que se encuentre actualmente.Puedes cambiar el valor de animation-play-state dinámicamente usando JavaScript.
Ejemplo: Pausar y reanudar una animación con un botón
HTML:
<div id="miCajaAnimada" class="caja-animada"></div>
<button id="botonPausarReanudar">Pausar / Reanudar</button>
Lenguaje del código: PHP (php)CSS:
@keyframes moverDerecha {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.caja-animada {
width: 50px;
height: 50px;
background-color: dodgerblue;
animation-name: moverDerecha;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-direction: alternate;
/* animation-play-state: running; por defecto */
}
Lenguaje del código: PHP (php)JavaScript:
const cajaAnimada = document.getElementById('miCajaAnimada');
const botonPausarReanudar = document.getElementById('botonPausarReanudar');
let estaPausada = false;
botonPausarReanudar.addEventListener('click', () => {
if (estaPausada) {
cajaAnimada.style.animationPlayState = 'running';
botonPausarReanudar.textContent = 'Pausar';
} else {
cajaAnimada.style.animationPlayState = 'paused';
botonPausarReanudar.textContent = 'Reanudar';
}
estaPausada = !estaPausada;
});Lenguaje del código: PHP (php)En este ejemplo, al hacer clic en el botón, se alterna el estado de animation-play-state de la caja entre paused y running.
Además de animation-play-state, JavaScript también puede:
animationstart, animationend, animationiteration) para ejecutar código en respuesta.animation-duration o animation-delay) antes de que comience o entre ciclos, aunque esto puede ser más complejo y a veces es más sencillo reiniciar la animación.