如何使用 javascript 将 svg use 元素插入 svg 组?

2024-04-21

我有一个 svg 文件,其中包含一个具有单行元素的组。我可以利用use元素并在我想要的任何位置制作多个参考副本。但是,我想使用 javascript 来添加和删除use动态元素。有没有办法使用javascript插入svguse我的行元素进入我的组?

<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);

演示在这里 http://jsfiddle.net/W3N7t/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 javascript 将 svg use 元素插入 svg 组? 的相关文章