启动svg动画onclick事件

时间:2018-01-18 08:16:36

标签: javascript jquery html css svg

当为SVG多边形的动画提供初始开始时间时,以下代码可以正常工作。但我无法弄清楚如何通过javascript / jquery触发它而不提供开始时间来" vbanim"动画。



$('button').click(function() {
  $('#v-b').beginElement();
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to draw</button>
<svg width="100px" height="100px" preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke-width="2" id="v-b" stroke-dasharray="3000"/>
  <animate xlink:href="#v-b" attributeName="stroke-dashoffset" from="3000" to="0" dur="2s" begin="indefinite" fill="freeze" id="vbanim"/>
  <animate xlink:href="#v-b" attributeName="fill" from="transparent" to="rgba(130,130,130,0.6)" dur="1s" begin="vbanim.end" fill="freeze"/>
</svg>
&#13;
&#13;
&#13;

我需要在点击按钮之后才发生stroke-dashoffset和fill动画,之前SVG根本不应该是可见的。谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

嗨,我不确定你想要实现什么..

请参阅示例代码的链接..

https://codepen.io/deibu21/pen/jYQLEO

我做的是我在animate标签中创建了一个类。 然后使用jquery的attr()来定位“begin”的属性 请参阅下面的代码..

$('button').click(function() {
  $('svg animate.anim1').attr("begin", 2);
  $('svg animate.anim2').attr("begin", 3);
})

希望这有帮助。

答案 1 :(得分:3)

首选工作解决方案,使用beginElement()在生成事件时无限期地启动动画。

注意 - beginElement()函数仅适用于原生javascript /而不是Jquery。

$('button').click(function() {
  document.getElementById('vbanim').beginElement();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to draw</button>
<svg width="100px" height="100px" preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke-width="0" id="v-b" stroke-dasharray="3000" />
  <animate class="anim1" xlink:href="#v-b" attributeName="stroke-dashoffset" from="3000" to="0" dur="2s" begin="indefinite" fill="freeze" id="vbanim"/>
  <animate class="anim2" xlink:href="#v-b" attributeName="fill" begin="vbanim.end" from="transparent" to="rgba(130,130,130,0.6)" dur="1s"  fill="freeze"/>
  <animate class="anim3" xlink:href="#v-b" attributeName="stroke-width" from="0" to="10" dur="0.2s" begin="vbanim.begin" fill="freeze" id=""/>
</svg>