首页 > 解决方案 > 将 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 文件

谢谢你的帮助

标签: javascripthtmlsvg

解决方案


您可以直接在 HTML 中使用 svgs。最简单的方法是在 HTML 中使用 SVG。您还可以在页面上重复使用 svg 形状,但图标具有 shadow-dom 边界。

如果您使用对象或 svg 标签,它会很好地呈现,但您将丢失 SVG 中有关类、ID 等的所有信息。

更多关于SVG 的 css-tricks信息

有关如何在 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();">


推荐阅读