CSS动画可通过原生animationend事件监听结束时机,支持现代浏览器,触发时提供animationName、elapsedTime等属性,需注意infinite动画不触发及内存泄漏问题。
可以,CSS 动画能通过 animationend 事件监听结束时机,这是浏览器原生支持的标准事件,无需额外库。
该事件在 CSS animation 完全播放完毕(包括正向播放、反向播放或循环中的最后一次)时触发。注意:它不适用于 transition(过渡),过渡对应的是 transitionend。
element.addEventListener('animationend', handler)
animation-play-state: paused 暂停后恢复并走完剩余时间,都可能触发——但强制中断(如移除 animation-name)不一定触发,需谨慎处理事件对象提供多个有用属性,帮助你判断具体是哪个动画结束:
event.animationName:返回触发事件的 @keyframes 名称(字符串),可用于区分多个动画event.elapsedTime:动画实际运行的秒数(不含 delay),对调试和逻辑判断很实用event.pseudoElement:若动画发生在伪元素(如 ::before)上,该值为 ::before 或 ::after;否则为 ''
实际使用中容易忽略几个细节:
animation-iteration-count: infinite,animationend 永远不会触发;若设为 3,则会在第 3 次结束后触
发一次(不是每次迭代都触发)animationend 的 elapsedTime 不包含 delay 时间,只算实际动画持续时间removeEventListener,或使用一次性监听({ once: true })webkitAnimationEnd,现在可直接用标准名常用于“播放一次 → 隐藏/重置元素”场景:
// HTML: Hello
// CSS: .slide-in { animation: slide 0.3s ease-out; }
// @keyframes slide { from { transform: translateX(-100px); } to { transform: translateX(0); } }
const box = document.getElementById('box');
box.addEventListener('animationend', function(e) {
if (e.animationName === 'slide') {
box.classList.remove('slide-in');
}
}, { once: true });