【问题标题】:Append nodetext to svg element将 nodetext 附加到 svg 元素
【发布时间】:2020-01-01 11:07:39
【问题描述】:

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

当我触发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>

【问题讨论】:

  • 创建一个 SVG 元素,而不是 HTML 文本节点。 MDN SVG 参考对所有 SVG 元素都有很好的概述。

标签: javascript html dom svg


【解决方案1】:

您还需要创建一个文本元素并将所有内容附加到一个 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>

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2012-01-11
    相关资源
    最近更新 更多