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

Web Animation API中animationend事件未触发原因及相关事件适配咨询

问题分析与解决

为什么animationend回调没执行?

  1. 事件类型不匹配:你绑定的是CSS动画标准的animationend事件,但Web Animation API创建的动画并不会触发这类CSS动画事件,它有一套独立的事件体系。
  2. 代码中的额外错误:
    • 你调用removeEventListener时,传入的change函数是新创建的实例,和之前绑定的函数不是同一个引用,所以移除操作无效,但这不是回调不执行的核心原因。
    • 获取body元素的方式错误:document.getElementById("body")无法正确获取body(除非你给body设置了id="body"),正确写法是document.body。

CSS动画事件是否适用于Web Animation API?

不适用。animationstart、animationend、animationiteration、animationcancel这类是**CSS动画(通过@keyframes和animation属性创建的动画)**的专属事件,Web Animation API有自己的事件体系:

  • 动画完成:监听finish事件(或使用onfinish回调)
  • 动画取消:监听cancel事件(或使用oncancel回调)
  • 动画移除:监听remove事件
  • 动画更新:监听update事件

修正后的代码示例

<!DOCTYPE html>
<html>
<body>    
    <div id="div1"></div>
</body>
<script>
const Divtarget = document.getElementById("div1");
class animasi{
  constructor(){
   this.effect1 = [{width: "200px", 
      backgroundColor:"blue"},{width: "1000px"} ];
   this.opsi1 = {duration: 5000, fill:  "forwards",
     delay: 5000};
    }
}
const getanime = new animasi();
const keyframEffect1 = new KeyframeEffect(Divtarget,getanime.effect1,getanime.opsi1);
const animation1 = new Animation(keyframEffect1,document.timeline);

animation1.play();

// 监听Web Animation API的finish事件
animation1.addEventListener('finish', function() {
    document.body.style.backgroundColor = "red";
});

// 如果需要移除监听,要保存函数引用
// const finishHandler = function() { document.body.style.backgroundColor = "red"; };
// animation1.addEventListener('finish', finishHandler);
// animation1.removeEventListener('finish', finishHandler);
</script>
</html>

内容的提问来源于stack exchange,提问作者Apabila X Terkadang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:42:45