Estoy tratando de agregar una animación a un elemento cuando alguien pasa el mouse sobre él.
Mi idea es agregar una clase con fotogramas clave y adjuntarle un detector de eventos de mouseover.
La razón por la que no uso CSS es porque quiero que la animación finalice incluso si el mouse deja el elemento antes de que finalice la animación. Por ejemplo, el mouse se mueve fuera del elemento cuando gira 180 grados (la animación completa es de 360 grados)
Pero lamentablemente no funciona y no sé por qué...
const item = document.querySelector('#rotate'); item.addEventListener('mouseover',function(e) { if(item) e.classList.add('rotate'); }); #div { width: 120px; height: 120px; background-color: orange; } .rotate { animation: rotating 1s ease 0s 1 normal forwards; } @keyframes rotating { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } <div id='rotate'></div>Ya estás en el camino correcto. Puede escuchar el evento animationend en el div y eliminar la clase de rotate cuando se activa el evento. He corregido su fragmento de ejemplo a continuación.
const item = document.querySelector('#rotate'); item.addEventListener('mouseover', function(e) { if(item) item.classList.add('rotate'); }); item.addEventListener('animationend', function(e) { if(item) item.classList.remove('rotate'); }); #rotate { width: 120px; height: 120px; background-color: orange; } .rotate { animation: rotating 1s ease 0s 1 normal forwards; } @keyframes rotating { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } <div id='rotate'></div>No cambia demasiado tu código.
e se refiere al evento que es un uso incorrecto del mismo, debe usar esto para apuntar al elemento actualmouseenter será mejor en esta situación cuando desee activar una animación cuando la use. const item = document.querySelector('#rotate'); item.addEventListener('mouseenter',function(e) { if(item) this.classList.add('rotate'); }); #rotate { width: 120px; height: 120px; background-color: orange; } .rotate { animation: rotating 1s ease 0s 1 normal forwards; } @keyframes rotating { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } <div id='rotate'></div>Yo diría que estabas bastante cerca. en primer lugar, debe cambiar #div a #rotate , luego agregar la clase directamente al elemento y luego, cuando finalice la animación, elimine la clase para que pueda ejecutarse nuevamente
const item = document.querySelector('#rotate'); item.addEventListener('mouseover', function(e) { item.classList.add('rotate'); }); item.addEventListener('animationend', function(e) { item.classList.remove('rotate'); }); #rotate { width: 120px; height: 120px; background-color: orange; } .rotate { animation: rotating 1s ease 0s 1 normal forwards; } @keyframes rotating { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } <div id='rotate'></div>