【问题标题】:Add g tag into svg tag without jquery在没有jquery的情况下将g标签添加到svg标签中
【发布时间】:2019-08-19 02:13:51
【问题描述】:

我有这段代码中的 svg 元素

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

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

【问题讨论】:

  • 只是createElementNS() 和appendChild(),不是吗?
  • 你能给我一些代码吗?

标签: javascript html reactjs svg


【解决方案1】:

应该是使用createElementNS和appendChild()的基本DOM操作:

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));
&lt;svg id="svg"&gt;&lt;/svg&gt;

【讨论】:

  • 嗨@Robby,感谢您的回答,但是我的 标签包含嵌套的 标签,所以我需要将Child g 标签附加到 g 标签中吗?
  • 确实如此。需要建立整个树。或者只是从字符串导入。
  • 我使用 parseFromString 来解析类似这样的内容:&lt;g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"&gt; 但我在某些“”中出现错误。
  • 在根 g 元素中需要一个 xmlns 属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多