首页 > 解决方案 > 在没有jquery的情况下将g标签添加到svg标签中

问题描述

我有这段代码中的 svg 元素

let chartSVG = ReactDOM.findDOMNode(this.refChart).children[0];

我想在该 chartSVG 中添加一个包含 g 标签的水印。

标签: javascripthtmlreactjssvg

解决方案


应该是使用createElementNSand的基本 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 内容作为字符串,则可以使用 aDOMParser()并导入片段:

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>


推荐阅读