一種可能的方法是向元素添加一個(gè)data-屬性,然后向其添加一個(gè)animationend事件監(jiān)聽器,以便在動(dòng)畫完成時(shí),事件監(jiān)聽器知道要移除該類。請(qǐng)參見(jiàn)下面的示例。
document.getElementById('clicky').addEventListener('click', () => { const element=document.querySelector('.highlight'); element.setAttribute('data-remove-class', 'highlight'); element.innerHTML='將在動(dòng)畫結(jié)束時(shí)移除類'; }); 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'>正在動(dòng)畫中!</div> <button id='clicky'>移除類</button>