我无法显示通过 JavaScript 构建的 SVG 图形。 svg 存储在零件中。我首先使用 html 正确显示 svg。如果我尝试使用 JavaScript 显示相同的图形,则不会显示任何内容。 这是我的完整代码:
<!DOCTYPE html>
<html>
<head>
<title> Testing SVG insertion</title>
<style>
svg.defs-only {
display: block;
position: absolute;
height: 0;
width: 0;
margin: 0;
padding: 0;
border: none;
overflow: hidden;
}
</style>
<svg class="defs-only">
<symbol id="shape" width="200" height="200" viewbox="0 0 200 200">
<circle cx="100" cy="100" r="100" fill="currentColor" />
</symbol>
</svg>
</head>
<body style='background-color: lightGray;'>
<h1> Testing SVG inclusion -- this works fine</h1>
<svg style='width: 200px; height: 200px;'>
<use xlink:href="#shape"></use>
</svg>
<h1> Testing SVG via javascript -- does not display anything </h1>
<div id='container'></div>
<script>
let div = document.getElementById ('container');
let svg = document.createElement ('svg');
svg.style.height = '200px';
svg.style.width = '200px';
let use = document.createElement ('use');
use.setAttribute("xlink:href", "#shape");
svg.appendChild (use);
div.appendChild (svg);
</script>
</body>
</html>```
您应该将
use.setAttribute("xlink:href", "#shape");
替换为 use.setAttribute("href", "#shape");
是由于 SVG 2.0 规范中弃用了 xlink。