我在 HTML5 文档中有一个内联 SVG,我想用 jQuery(如果需要,也可以用纯 JavaScript)添加。
我知道如何添加矩形、圆形或其他形式,但我还不能重用现有的 .
这是对 jsFiddle 的测试:http://jsfiddle.net/nhoizey/uDVbn/
SVG:
<svg width="300" height="300">
<symbol id="piece"><circle cx="50" cy="50" r="40" fill="green" /></symbol>
<circle cx="70" cy="90" r="20" stroke="blue" fill="white" />
</svg>
JavaScript:
// it works!
var rect = $(document.createElementNS("http://www.w3.org/2000/svg","rect"))
.attr({
x: 10,
y: 30,
width: 50,
height: 70,
stroke: "red",
fill: "white"
});
$("svg").append(rect);
// it doesn't work
var newPiece = $(document.createElementNS("http://www.w3.org/2000/svg","use"))
.attr({
"xlink:href": "#piece",
transform: "translate(100, 100)"
});
$("svg").append(newPiece);
我知道有一个 jQuery SVG 插件,但希望它尽可能简洁。
最佳答案
添加 href 属性的正确方法是使用 setAttributeNS。
useElement.setAttributeNS("http://www.w3.org/1999/xlink", 'href', '#piece');
关于javascript - 如何使用 jQuery(或需要时的纯 JavaScript)将 <use> 添加到内联 SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9032299/