在 HTML 中使用 javascript 动态创建 SVG 元素

新手上路,请多包涵

我想在 HTML 页面内创建一个矩形,然后在该矩形上写一些文本。我还需要该文本成为超链接。这就是我所做的,但它不起作用:

     <!DOCTYPE html>
<html>
<body>

<script>

    var svg   = document.documentElement;
    var svgNS = svg.namespaceURI;

    var rect = document.createElementNS(svgNS,'rect');
    rect.setAttribute('x',5);
    rect.setAttribute('y',5);
    rect.setAttribute('width',500);
    rect.setAttribute('height',500);
    rect.setAttribute('fill','#95B3D7');
    svg.appendChild(rect);
    document.body.appendChild(svg);

    var h=document.createElement('a');
    var t=document.createTextNode('Hello World');
    h.appendChild(t);
    document.body.appendChild(h);

</script>

</body>
</html>

你能帮忙吗?谢谢。

原文由 user2746087 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

改变

var svg   = document.documentElement;

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

这样您就可以创建一个 SVG 元素。

要使链接成为超链接,只需添加 href 属性:

 h.setAttributeNS(null, 'href', 'http://www.google.com');

示范

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 4.0 许可协议

可以使用片段轻松添加元素。

例子

 <input style="width:300px" type="text" placeholder="Input something to change the text." /><br>
<script>
const frag = document.createRange().createContextualFragment(`
<svg width="250" height="250">
  <rect x="0" y="0" width="250" height="250" fill="#95B3D7"></rect>
  <a href="https://www.google.com" style="cursor: pointer" target="_blank">
    <text x="10" y="130" style="
      font-size: 48px;
      fill:#faff00;">
      Hello world</text>
  </a>
</svg>
      `)
      const textElem = frag.querySelector("text")
      document.querySelector("input").onchange = (e) => {
        textElem.textContent = e.target.value
      }
      document.body.append(frag)
</script>

原文由 Carson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题