如何使用javascript在svg组中插入svg use元素? [英] How do I use javascript to insert an svg use element into an svg group?
本文介绍了如何使用javascript在svg组中插入svg use元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个svg文件,其中包含一个具有单个线元素的组。我可以使用use元素,并在任何位置,我想要他们几个参考副本。但是,我想使用javascript来动态添加和删除使用元素。有没有办法使用javascript来插入一个svg使用元素的行我的组?
< svg version = 1.1id =ex1-3rds-quarter-sxmlns =http://www.w3.org/2000/svgxmlns:xlink =http://www.w3.org/1999/xlinkx =0px
y =0pxwidth =323.333pxheight =55.333pxviewBox =0 0 323.333 55.333enable-background =new 0 0 323.333 55.333
xml:space =preserve>
< g id =ledgerlines>
< line id =MidCLine1fill =nonestroke =#000000stroke-width =0.75stroke-miterlimit =10x1 =48.09y1 =41.694x2 = 57.924y2 =41.694/>
< / g>
< / svg>
h2_lin>解决方案
var svgns =http://www.w3.org/2000/svg;
var xlinkns =http://www.w3.org/1999/xlink;
//获取对< g> element
var g = document.getElementById(ledgerlines);
//创建< use>元素
var use = document.createElementNS(svgns,use);
//添加'href'属性(使用xlink命名空间)
use.setAttributeNS(xlinkns,href,#MidCLine1);
//将行向下偏移10
use.setAttribute(y,10); // offset = y + 10
//添加< use>到< g>
g.appendChild(use);
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 am wanting 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>
Thanks, --christopher
解决方案
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);
这篇关于如何使用javascript在svg组中插入svg use元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文