SVG:动态添加动画元素

时间:2018-03-12 22:04:24

标签: javascript css svg svg-animate

我尝试动态添加animate元素到我的path元素,这是正确的。我的HTML:

<g id="3" class="cluster loop-node">
<path fill="#edf1f2" stroke="#028d35" d="M92,-16C92,-16 408,-16 408,-16 414,-16 420,-22 420,-28 420,-28 420,-88 420,-88 420,-94 414,-100 408,-100 408,-100 92,-100 92,-100 86,-100 80,-94 80,-88 80,-88 80,-28 80,-28 80,-22 86,-16 92,-16"></path>
<text text-anchor="start" x="213.5547" y="-79.4" font-family="Times,serif" font-size="14.00" fill="#000000">1:11</text>
<text text-anchor="start" x="243.8131" y="-79.4" font-family="Times,serif" font-size="14.00" fill="#000000"> (Loop)</text>
</g>

我通过javascript:

添加我的animate元素('<animate attributeType="XML" attributeName="stroke-width" values="6;1;6;1" dur="2s" repeatCount="3"></animate>'
$("#3").find("path").append('<animate attributeType="XML" attributeName="stroke-width" values="6;1;6;1" dur="2s" repeatCount="indefinite"></animate>')

之后,正确添加了animate标记:

<g id="3" class="cluster loop-node">
<path fill="#edf1f2" stroke="#028d35" d="M92,-16C92,-16 408,-16 408,-16 414,-16 420,-22 420,-28 420,-28 420,-88 420,-88 420,-94 414,-100 408,-100 408,-100 92,-100 92,-100 86,-100 80,-94 80,-88 80,-88 80,-28 80,-28 80,-22 86,-16 92,-16"><animate attributetype="XML" attributename="stroke-width" values="6;1;6;1" dur="2s" repeatcount="indefinite"></animate></path>
<text text-anchor="start" x="213.5547" y="-79.4" font-family="Times,serif" font-size="14.00" fill="#000000">1:11</text>
<text text-anchor="start" x="243.8131" y="-79.4" font-family="Times,serif" font-size="14.00" fill="#000000"> (Loop)</text>
</g>

问题是当我以这种方式(以编程方式)插入动画时不会显示动画。如果我从头开始插入相同的html,那么它可以工作,但不是在我想以编程方式插入它们时。 我想也许我应该重新加载div,但动画没有运行。 我的代码有什么问题?

1 个答案:

答案 0 :(得分:3)

你必须用.beginElement()开始动画 这不是一个jquery方法,因此你不能将它与jquery对象一起使用。请改用Dom对象

var myanim=document.createElementNS("http://www.w3.org/2000/svg", 'animate');
myanim.setAttribute("id","myAnimation"); 
myanim.setAttribute("attributeType","XML"); 
myanim.setAttribute("attributeName","stroke-width"); 
myanim.setAttribute("values","6;1;6;1"); 
myanim.setAttribute("dur","2s"); 
myanim.setAttribute("repeatCount","3"); 
var myPath = document.getElementById("path1");

myPath.appendChild(myanim);

function myFunction() {
console.log('hello')
//$("#myAnimation").beginElement();
document.getElementById("myAnimation").beginElement();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()">Click me</button>

<svg width="320" height="320" viewBox="0 0 320 320">
<path
            id="path1" fill="#edf1f2" stroke="#ff8d35"
            d="M160,100 Q200,100,200,300 Q100,300,100,200 Z">


                </path>

 </svg>