I have an svg file containing a group with a single line element. I can make use of the use element and make several reference copies in any position I want them. However, I want to use javascript to add and remove the use element dynamically. Is there a way to use javascript to insert an svg use element of my line into my group?

<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>
有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top