我有来自此代码的 svg 元素
let chartSVG = ReactDOM.findDOMNode(this.refChart).children[0];
我想在该 ChartSVG 中添加包含 g 标签的水印。
最佳答案
应该使用 createElementNS
进行基本的 DOM 操作和 appendChild()
:
const xmlns = "http://www.w3.org/2000/svg";
const rect = document.createElementNS(xmlns, 'rect');
rect.setAttributeNS (null, "width", 50);
rect.setAttributeNS (null, "height", 50);
const g = document.createElementNS(xmlns, 'g');
g.appendChild(rect);
const svg = document.getElementById('svg');
svg.appendChild(g);
<svg id="svg"></svg>
或者,如果您将 SVG 内容作为字符串,则可以使用 DOMParser()
并导入片段:
const g = new DOMParser().parseFromString(
'<g xmlns="http://www.w3.org/2000/svg"><rect width="50" height="50"/></g>',
'application/xml');
const svg = document.getElementById('svg');
svg.appendChild(svg.ownerDocument.importNode(g.documentElement, true));
<svg id="svg"></svg>
关于javascript - 在不使用jquery的情况下将g标签添加到svg标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55395377/