【问题标题】:Start a svg animation onclick event启动 svg 动画 onclick 事件
【发布时间】: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 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>

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

【问题讨论】:

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

标签: javascript jquery html css svg


【解决方案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 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>

【讨论】:

    【解决方案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 多边形完全不可见。
    • 没关系,我明白了。添加另一个动画有帮助。无论如何,感谢您的帮助。 :)
    • 如果超过指定的时间限制,使用它的动画将不流畅
    猜你喜欢
    • 2019-06-14
    • 2012-08-20
    • 2020-07-09
    • 2015-05-27
    • 2023-03-22
    • 2021-06-28
    • 2021-03-03
    • 2016-06-08
    • 2013-10-11
    相关资源
    最近更新 更多