You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JavaScript创建的动画无法触发animationstart事件监听器?

问题原因与解决办法

你遇到的问题是因为**animationstart是CSS动画专属的事件**,而你用的是Web Animations API(通过Animation和KeyframeEffect创建的动画),这类动画的生命周期事件需要绑定在Animation实例本身,而非动画元素上。

解决步骤

把原来绑定在元素上的animationstart监听,改成绑定到你创建的animation对象上,事件名用start(不是animationstart):

方法1:使用addEventListener绑定事件

let anim = document.getElementById("anim");

const animkeyFrames = new KeyframeEffect(
  anim,
  [{
      transform: `translate3d(0px, 0px, 0px)`
    },
    {
      transform: `translate3d(0px, ${200}px, 0px)`
    },
  ], {
    duration: 1000,
    iterations: 1, // 建议用数字1,而非字符串"1"
  },
);
let animation = new Animation(animkeyFrames, document.timeline);

// 关键修改:给animation对象绑定start事件
animation.addEventListener('start', () => {
  console.log("STARTED");
})

animation.play();

方法2:直接使用onstart回调属性

也可以简化写法,直接给Animation实例的onstart赋值:

animation.onstart = () => {
  console.log("STARTED");
};

补充说明

  • CSS动画(通过@keyframes和animation属性实现)才会触发元素上的animationstart、animationend事件
  • Web Animations API的动画事件包括:start、finish、cancel、remove等,都需要绑定到Animation实例上

内容的提问来源于stack exchange,提问作者AshBoomstick1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:24:50