javascript - 如何使用 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 来做到这一点?
解决方案
您也可以使用 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" />
推荐阅读
- python - 将 Django 从 2.1 升级到 2.2.13 时如何修复 pyodbc 依赖错误?
- openstack - openstack 错误:virNetSocketReadWire:1806:读取数据时文件结束:输入/输出错误
- python - 使用 BeautifulSoup 在 Python 中抓取特定的 div
- php - 使用键和值创建PHP数组时如何分配变量
- mongodb - 如何在 MongoDB 中的 $group 内创建嵌套数组?
- sql - 定期进行 DB 到 DB 映射
- javascript - 如何获取嵌套打字稿接口的json字符串
- azure - 使用 Azure B2C 自定义策略获取 userPrinciaplName
- python - 训练后量化后的“模型未量化”取决于模型结构?
- merge - 关于合并转换