Web Animation API中animationend事件未触发原因及相关事件适配咨询
问题分析与解决
为什么animationend回调没执行?
- 事件类型不匹配:你绑定的是CSS动画标准的
animationend事件,但Web Animation API创建的动画并不会触发这类CSS动画事件,它有一套独立的事件体系。 - 代码中的额外错误:
- 你调用
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
相关产品推荐
相关产品推荐

