
web animation api 不触发 css 动画事件(如 animationend),而应使用原生 animation 对象的 finish、cancel、start 等事件;本文详解如何正确监听动画完成,并给出可运行示例与关键注意事项。
web animation api 不触发 css 动画事件(如 animationend),而应使用原生 animation 对象的 finish、cancel、start 等事件;本文详解如何正确监听动画完成,并给出可运行示例与关键注意事项。
在 Web Animation API 中,animationstart、animationend、animationiteration 和 animationcancel 这类事件仅适用于 CSS 样式驱动的动画(即通过 @keyframes + animation CSS 属性定义的动画),并不适用于通过 Animation 构造函数创建的 JavaScript 动画。你代码中使用的是纯 JS 创建的 Animation 实例(new Animation(...)),因此绑定到元素上的 animationend 监听器完全不会被触发——这是根本性误解,也是问题根源。
✅ 正确做法是:直接为 Animation 对象添加事件监听器,使用其原生生命周期事件:
- 'finish':动画自然播放结束(到达终点且未被中断)时触发;
- 'cancel':动画被 animation.cancel() 主动取消时触发;
- 'start':动画开始播放(含从暂停恢复)时触发;
- 'remove':动画被显式移除(animation.remove())时触发。
注意:'start' 事件需在调用 play() 之前注册才可靠捕获(因播放可能同步触发)。
以下是修正后的完整可运行示例(已优化时长便于测试):
<style>
#div1 { width: 200px; height: 100px; background-color: blue; }
</style><div id="div1"></div>
<script>
const divTarget = document.getElementById("div1");
class Animasi {
constructor() {
this.effect1 = [
{ width: "200px", backgroundColor: "blue" },
{ width: "1000px", backgroundColor: "lightblue" }
];
this.options1 = {
duration: 1000,
fill: "forwards",
delay: 300
};
}
}
const getAnime = new Animasi();
const keyframeEffect = new KeyframeEffect(divTarget, getAnime.effect1, getAnime.options1);
const animation = new Animation(keyframeEffect, document.timeline);
// ✅ 正确:监听 Animation 实例的 'finish' 事件
animation.addEventListener('finish', () => {
document.body.style.backgroundColor = "red";
console.log("Animation finished successfully.");
});
// ✅ 可选:监听 'cancel' 以处理异常终止
animation.addEventListener('cancel', () => {
console.warn("Animation was cancelled.");
});
// ⚠️ 注意:必须在 play() 之前注册 'start' 才能确保捕获
animation.addEventListener('start', () => {
console.log("Animation started.");
});
animation.play();
</script>
? 关键注意事项:
- 不要对 DOM 元素使用 animationend 监听 JS 动画——它只响应
- finish 事件在 fill: "forwards" 下仍会正常触发(与视觉状态无关,仅与播放逻辑相关);
- 若动画被 pause() 后未再 play(),不会触发 finish;若调用 cancel(),则触发 cancel 而非 finish;
- document.timeline 是默认时间轴,生产环境建议检查其可用性(如兼容性处理);
- 动画对象需保持引用,否则可能被垃圾回收,导致事件监听器失效(尤其在闭包或异步上下文中)。
掌握这一区分,是构建健壮交互动画的基础。始终牢记:CSS 动画用 CSS 事件,JS 动画用 Animation 事件。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











