javascript - 将 SVG 文件插入 HTML
问题描述
我有 3 个文件:test.html、test.js 和 test.svg
我正在尝试将不同的文件调用为 HTML,但文件 svg 不起作用
测试.html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Using SVG as an object</title>
<link href="index.css" rel="stylesheet" />
</head>
<body>
<h1>Test</h1>
<script type="text/javascript" src="test.js"></script>
<object data="test.svg" width="300" height="300"> </object> <!-- Not working -->
<input type="button" value="Start Animation" onclick="startAnimation();">
<input type="button" value="Stop Animation" onclick="stopAnimation();">
</body>
</html>
测试.js
var timerFunction = null;
function startAnimation() {
if(timerFunction == null) {
timerFunction = setInterval(animate, 20);
}
}
function stopAnimation() {
if(timerFunction != null){
clearInterval(timerFunction);
timerFunction = null;
}
}
function animate() {
var circle = document.getElementById("circle1");
var x = circle.getAttribute("cx");
var newX = 2 + parseInt(x);
if(newX > 500) {
newX = 20;
}
circle.setAttribute("cx", newX);
}
测试.svg
<svg width="500" height="100">
<circle id="circle1" cx="20" cy="20" r="10"
style="stroke: none; fill: #ff0000;"/>
</svg>
我不明白为什么我不能用对象插入 svg 文件
谢谢你的帮助
解决方案
您可以直接在 HTML 中使用 svgs。最简单的方法是在 HTML 中使用 SVG。您还可以在页面上重复使用 svg 形状,但图标具有 shadow-dom 边界。
如果您使用对象或 svg 标签,它会很好地呈现,但您将丢失 SVG 中有关类、ID 等的所有信息。
有关如何在 css-tricks 上对 SVG 中的形状进行分组和重用的更多信息(还有一个,也在 css-tricks 上)
var timerFunction = null;
function startAnimation() {
if (timerFunction == null) {
timerFunction = setInterval(animate, 20);
}
}
function stopAnimation() {
if (timerFunction != null) {
clearInterval(timerFunction);
timerFunction = null;
}
}
function animate() {
var circle = document.getElementById("circle1");
var x = circle.getAttribute("cx");
var newX = 2 + parseInt(x);
if (newX > 500) {
newX = 20;
}
circle.setAttribute("cx", newX);
}
<svg width="500" height="100">
<circle id="circle1" cx="20" cy="20" r="10"
style="stroke: none; fill: #ff0000;"/>
</svg>
<input type="button" value="Start Animation" onclick="startAnimation();">
<input type="button" value="Stop Animation" onclick="stopAnimation();">
推荐阅读
- node.js - 如何在没有对象'_text'道具的情况下使用xml-js
- mysql - 用sql简化
- android - 有条件的许可声明
- python - csv到动态html刷新
- octave - 从 Octave 数据帧访问数据时出现问题
- wordpress - Wordpress - 如何迁移和保留帖子 URL
- sql - 如何选择所有出现的用户名末尾有数字?
- android - Android网页上传无法选择某些pdf文件
- javascript - 正则表达式/Javascript,用绝对值转换字符串 |x| 到 abs(x)
- javascript - Rails 没有路由匹配 AJAX 请求中的 PATCH