[英]How can I add a <use> to an inline SVG using jQuery (or plain JavaScript if needed)?
我在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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.