[英]Javascript SVG <g> tag
我正在尝试做的事情:将 svg 插入最里面的 g 标签
到目前为止我做了什么:
let svg = document.querySelector('svg');
let g = svg.getElementsByClassName('srd-default-link');
let shape = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
shape.id = 'circle';
shape.setAttribute('cx', 25);
shape.setAttribute('cy', 25);
shape.setAttribute('r', 20);
shape.setAttribute('style', 'fill: green');
g[0].appendChild(shape);
}
结果:只能插入第一层g标签,不能插入最里面的g标签
在您的源代码中有两个主要问题:
id
值。 根据 HTML 文档, id
用作元素的唯一标识符。svg.appendChild(shape);
将圆圈“附加”到<svg>
而不是<g>
标记;你可以做类似的事情:
var svgElem = document.createElementNS("http://www.w3.org/2000/svg", "svg"); //create <svg>
var g = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create <g>
g.classList.add("myClass");
svgElem.appendChild(g); //append <g> inside <svg>
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); //create <circle>
g.appendChild(circle); //append <circle> inside <g>
var g_2 = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create another <g>
g_2.classList.add("myClass");
svgElem.appendChild(g_2); //append <g> inside <svg>
var coll = svgElem.getElementsByClassName("myClass"); //coll contains HTMLCollection
/* You cannot use coll.appendChild(circle);*/
coll[0].appendChild(circle); //append <circle> to the first <g> returned by getElementsByClassName("myClass");
我找到了它不起作用的原因。 我放了一个if条件,
if (g.length !== 0) g[0].appendChild(shape);
我把它放在第一行的 componentDidUpdate 中。 感谢@Wolfetto 在最初部分的帮助。 我会把它留在这里给以后需要的人。
if (g.length !== 0) {
for (let i = 0; i < g[0].childNodes.length; i++) {
let item = g[0].childNodes[i];
if (item.nodeName === 'g') item.appendChild(shape);
}
}
这是将 append 形状放入 svg 元素的最内层 g 标记的代码。 我欢迎任何改进代码的建议(如果有的话)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.