首页 > 解决方案 > 将 nodetext 附加到 svg 元素

问题描述

我会将文本节点附加到gsvg 元素。

触发时屏幕上没有打印任何内容my function

但是当我将TextNode元素直接附加到正文时它起作用了

function myFunction() {
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  var t = document.createTextNode("Hello World");
  document.body.appendChild(g);
  g.appendChild(t)
}
<p>Click the button to create a Text Node.</p>

<button onclick="myFunction()">Try it</button>

此代码无需使用即可工作g

function myFunction() {
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  var t = document.createTextNode("Hello World");
  document.body.appendChild(t);
}
<p>Click the button to create a Text Node.</p>

<button onclick="myFunction()">Try it</button>

标签: javascripthtmldomsvg

解决方案


您还需要创建一个文本元素并将所有内容附加到 svg 元素。在这种情况下,我使用带有 viewBox 的 svg 元素,尽管我没有为 x 和 y 属性设置任何值,但它允许我查看文本。根据您的 viewBox,您可能还需要设置这些属性。

function myFunction() {
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
  text.textContent = "Hello World";
  g.appendChild(text);
  svg.appendChild(g);
 
}
<p>Click the button to create a Text Node.</p>

<svg id="svg" viewBox="-100 -50 200 100" width="200"></svg>

<button onclick="myFunction()">Try it</button>


推荐阅读