Quiero hacer algo cuando finalice la primera animación> comience otra animación> y cuando la segunda también esté animada> alerte algo
Pero aquí, ¿la alerta también se muestra después de que finaliza la primera animación? ¿Por qué está pasando esto? incluso cuando he dicho que muestre la alerta cuando el animado
<div id="one"> <div id="second"> </div> </div> <button id="mybtn"> Animate </button> @keyframes test { 100% { height: 0px; } } #one { height: 100px; width: 100px; background: red; } #second { height: 70px; width: 70px; background: blue; } #mybtn { margin-top: 50px; } const overlay = document.getElementById('one'); const second = document.getElementById('second'); const mybtn = document.getElementById('mybtn'); mybtn.addEventListener('click', function(){ second.style.animation = '4000ms ease forwards test'; second.addEventListener("animationend", function() { one.style.animation = '4000ms ease forwards test'; one.addEventListener("animationend", function() { alert('hello'); }); }); });aquí está el código jsfiddle completo: - https://jsfiddle.net/hjqxvy89/
Evidentemente, el elemento principal también recibe el evento animationend en sus elementos secundarios, por lo que tiene dos opciones, verifique el event.target . objetivo:
const overlay = document.getElementById('overlay'); const second = document.getElementById('second'); const mybtn = document.getElementById('mybtn'); mybtn.addEventListener('click', function(){ second.style.animation = '4000ms ease forwards test'; second.addEventListener("animationend", function() { overlay.style.animation = '4000ms ease forwards test'; overlay.addEventListener("animationend", function(e) { if (e.target === overlay) alert('hello'); }); }); }); @keyframes test { 100% { height: 0px; } } #overlay { height: 100px; width: 100px; background: red; } #second { height: 70px; width: 70px; background: blue; } #mybtn { margin-top: 50px; } <div id="overlay"> <div id="second"> </div> </div> <button id="mybtn"> Animate </button> o simplemente use event.preventPropagation() en el controlador de eventos principal:
const overlay = document.getElementById('overlay'); const second = document.getElementById('second'); const mybtn = document.getElementById('mybtn'); mybtn.addEventListener('click', function(){ second.style.animation = '4000ms ease forwards test'; second.addEventListener("animationend", function(e) { e.stopPropagation(); overlay.style.animation = '4000ms ease forwards test'; overlay.addEventListener("animationend", function() { alert('hello'); }); }); }); @keyframes test { 100% { height: 0px; } } #overlay { height: 100px; width: 100px; background: red; } #second { height: 70px; width: 70px; background: blue; } #mybtn { margin-top: 50px; } <div id="overlay"> <div id="second"> </div> </div> <button id="mybtn"> Animate </button>también: ¿el evento animationend también se activa al final de las animaciones de los elementos secundarios?