首页 > 解决方案 > 如何使用 JavaScript 触发 SVG 动画?(没有 jQuery)

问题描述

我有一个用我发现的这个示例动画的 SVG 线条路径:

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0%;
  top: 0%;
  display: block;
  background: transparent;
}

.path {
  stroke: black;
  stroke-dasharray: 290;
  stroke-dashoffset: 130;
  animation: dash 6s 0s forwards infinite;
  stroke-width: 2px;
  stroke-linecap: round;
  stroke-linejoin: round;
}

@keyframes dash {
  from {
    stroke-dashoffset: 290;
  }
  to {
    stroke-dashoffset: 0;
  }
}
<svg viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
<path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent"></path>
</svg>

它工作正常,但在页面加载时触发。有没有办法(比如说用一个按钮)使用 JavaScript 触发这个动画?

我可以处理 JS,但我是 CSS 和 SVG 动画的菜鸟。

谁能给我一个例子来说明我如何使用我的实际 CSS 来做到这一点?

标签: javascriptcsssvg

解决方案


您也可以使用 SMIL 动画语法而不是 CSS 动画。不可否认,这具有无法在 Microsoft 浏览器(IE 和 Edge)中运行的缺点。

var animation = document.getElementById("dash");

function showSVG() {
  animation.beginElement();
}
svg {
  position: relative;
  width: 100%;
  height: 150px;
  left: 0%;
  top: 0%;
  display: block;
  background: transparent;
}

.path {
  stroke: black;
  stroke-dasharray: 290;
  stroke-dashoffset: 290;
  stroke-width: 2px;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<button id="button" onclick="showSVG()">Click</button>
<svg id="svg" viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
  <path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent">
  <animate id="dash" 
    attributeName="stroke-dashoffset"
    from="290" to="0"
    begin="indefinite" 
    dur="6s" 
    fill="freeze" />
  </path>
</svg>

每次单击时,此动画都会运行一次。如果您希望它以固定间隔重复,如 CSSanimation-repeat: infinite规定,请使用

<animate id="dash" attributeName="stroke-dashoffset"
    from="290" to="0"
    begin="indefinite" dur="6s" repeatCount="indefinite" />

推荐阅读