启动 svg 动画 onclick 事件

Posted

技术标签:

【中文标题】启动 svg 动画 onclick 事件【英文标题】:Start a svg animation onclick event 【发布时间】:2018-06-27 05:58:44 【问题描述】:

当为 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   preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke- 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>

我需要 stroke-dashoffset 和填充动画仅在单击按钮后发生,在此之前,SVG 根本不可见。感谢您的帮助。

【问题讨论】:

请检查控制台。 1. $('v-b') 选择器不正确 2. $('#v-b').beginElement();也不行 可能重复:***.com/questions/40488526/… 是的,这是我的错,但我提到了另一个似乎不起作用的答案,它是一个多边形而不是路径动画,所以我认为这不一样。 我只需要一种解决方法来实现我在问题中提到的内容,在单击按钮时启动动画并且在此之前不应显示多边形。如果您将第一个动画标签中的开始更改为 0,您将看到所需的输出。 不要在问题内添加解决方案...您接受了一个答案,所以要么编辑此答案,要么添加您自己的答案并接受它 【参考方案1】:

使用 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   preserveAspectRatio="false" viewBox="0 0 500 800">
  <polygon points="20,20 490,20 490,780 20,780" stroke="black" fill="transparent" stroke- 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>

【讨论】:

【参考方案2】:

您好,我不确定您想要达到什么目的..

请查看示例代码的链接..

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

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

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

希望这会有所帮助。

【讨论】:

这与我所需要的很接近,但在单击按钮绘制之前,SVG 多边形完全不可见。 没关系,我明白了。添加另一个动画有帮助。无论如何,感谢您的帮助。 :) 如果超过指定的时间限制,使用它的动画将不流畅

以上是关于启动 svg 动画 onclick 事件的主要内容,如果未能解决你的问题,请参考以下文章

在事件中动态更改 animateMotion SVG 元素的路径

将 onclick 事件添加到 SVG 元素

SVG 检测“填充:无”上的 Onclick 事件

提交表单时捕获 onClick 事件

在事件动作上突出显示 SVG <g> 中的多个路径元素

使用javascript "onload "启动SVG动画