Cod*_*ope 3 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>
Run Code Online (Sandbox Code Playgroud)
我通过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>')
Run Code Online (Sandbox Code Playgroud)
之后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>
Run Code Online (Sandbox Code Playgroud)
但问题是当我以这种方式(以编程方式)插入动画时没有显示动画。如果我html从一开始就插入相同的内容,那么它就可以工作,但当我想以编程方式插入它们时就不行了。我想也许我应该重新加载div,但动画没有运行。我的代码有什么问题?
您必须使用.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();
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)