2014-05-05 164 views
1

我有一个svg文件,其中包含一个具有单个线条元素的组。我可以使用使用元素,并在我想要的任何位置创建几个参考副本。但是,我想要使用JavaScript来动态添加和删除使用元素。有没有办法使用JavaScript来插入我的行的svg使用元素到我的组?如何使用javascript将svg使用元素插入svg组?

<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" 
y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333" 
xml:space="preserve"> 
<g id="ledgerlines"> 
    <line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/> 
</g> 
</svg> 

感谢, --christopher

回答

10
var svgns = "http://www.w3.org/2000/svg"; 
var xlinkns = "http://www.w3.org/1999/xlink"; 

// Get a reference to the <g> element  
var g = document.getElementById("ledgerlines"); 

// Create a <use> element 
var use = document.createElementNS(svgns, "use"); 
// Add an 'href' attribute (using the "xlink" namespace) 
use.setAttributeNS(xlinkns, "href", "#MidCLine1"); 
// Offset the line down by 10 
use.setAttribute("y", "10"); // offset = y+10 

// Add the <use> to the <g> 
g.appendChild(use); 

Demo here

+0

优秀,谢谢。然后,我会使用removechild命令在不再需要时将其删除? –

+0

是的,这是正确的。 –