One possible approach would be to add a data-attribute to the element and then add an animationend event listener to it so that when the animation completes, the event listener knows to remove the class. See example below.
document.getElementById('clicky').addEventListener('click', () => { const element=document.querySelector('.highlight'); element.setAttribute('data-remove-class', 'highlight'); element.innerHTML='將在動畫結(jié)束時移除類'; }); document.querySelector('.highlight').addEventListener('animationend', (e) => { const removeClass = e.target.getAttribute('data-remove-class'); if (removeClass == 'highlight') { e.target.classList.remove(removeClass); e.target.removeAttribute('data-remove-class'); e.target.innerHTML='類已移除!'; } });
.highlight { animation-name: highlight; animation-duration: 3s; } @keyframes highlight { 0% { background-color: yellow; } 99.99% { background-color: orange; } }
<div class='highlight'>正在動畫中!</div> <button id='clicky'>移除類</button>