Why does this JS-created SVG not work in

2019-05-09 17:21发布

Consider this simple SVG SMIL animation:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-50 -50 100 100">
  <circle r="40" fill="red">
    <animate
      attributeType="CSS" begin="click"
      attributeName="fill" to="blue" dur="0.3s" fill="freeze"/>
  </circle>
</svg>

This works correctly in Chrome v18 on Windows (modulo a bug with holding the color):
http://phrogz.net/svg/change-color-on-click-simple.svg

When I generate the <animate> element using JavaScript, all works well in Firefox, Safari, and Opera, but not Chrome. In Chrome, nothing happens when I click on the circle.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-50 -50 100 100">
  <circle r="40" fill="red"/>
  <script>
    var c = document.querySelector('circle');
    createOn(c,'animate',{
      attributeType:'CSS', begin:'click',
      attributeName:'fill', to:'blue',
      dur:'0.3s', fill:'freeze'
    });
    function createOn(el,name,attrs){
      var e = el.appendChild(document.createElementNS(el.namespaceURI,name));
      for (var name in attrs) e.setAttribute(name,attrs[name]);
      return e;
    }
  </script>

See this JavaScript version here:
http://phrogz.net/svg/change-color-on-click-simple-js.svg

There are no script errors in the console. The content of the first example was actually generated by choosing Copy As HTML from the Chrome Developer Tools after loading the second example, so I know that it is producing the correct attribute names and values. The namespaceURI of the <animate> element is the same between both (the SVG namespace), as is the namespaceURI of all attributes (null).

Is there a way to get JS-generated <animate> elements to work in Chrome?

1条回答
We Are One
2楼-- · 2019-05-09 17:45

If I define the attributes before appending the animation, it appears to work.

http://jsfiddle.net/VFUHk/

查看更多
登录 后发表回答