[英]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.