Skip to main content
 首页 » 编程设计

javascript之通过 Javascript DOM 完成时未调用 SVG 动画元素的 endEvent 处理程序

2025年12月25日31mq0036

我正在通过 Javascript DOM 使用 HTML5 SVG 构建图形。

我使用动画沿着它的 x 坐标(y 常量)移动一个 svg 元素(它是主 svg 元素的子元素)。

var animate = document.createElementNS("http://www.w3.org/2000/svg", "animate"); 
animate.id = i; 
animate.setAttribute('attributeName','x'); 
animate.setAttribute('begin','indefinite'); 
animate.setAttribute('dur','1s'); 
animate.setAttribute('fill','freeze'); 
animate.addEventListener('endEvent',animationEnd,false); 
svgChild.appendChild(animate); 

稍后我通过 svg 元素访问 animate 元素,并开始动画

svgChild.firstChild.setAttribute('from',xFrom); 
svgChild.firstChild.setAttribute('to',xTo); 
svgChild.firstChild.beginElement() 

到这里为止一切正常。

但是在动画结束时,不会调用为其注册的处理程序。

下面的方法我也试过了,还是不行。

animate.setAttribute('end',animationEnd); 

我在通过 Javascript DOM 构建 SVG 的论坛上进行了广泛搜索。但是找不到任何关于通过 javascript DOM 注册动画事件属性的帮助。

我在本论坛查看的一些问题

How to add an animated svg via javascript?

Check when an animation has ended in SVG

请您参考如下方法:

我是这样做的。

  ani.setAttributeNS(null,"onend", "console.log('ding.')"); 
  // ani.addEventListener("onend", "console.log('ding.')", false);  // cannot do it like this - events all happen right away