通过JavaScript动态设置文本SVG元素

33

我正在通过JavaScript创建SVG元素,一切都正常,但当我创建一个文本SVG元素并定义其内容时,浏览器却无法呈现值,尽管我使用firebug检查代码时,该值确实存在于代码中。

代码如下:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xlink','http://www.w3.org/1999/xlink');
svg.setAttribute('width','187');
svg.setAttribute('height','234');

var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('width','187');
rect.setAttribute('height','234');
rect.setAttribute('fill','#fff');
rect.setAttribute('stroke','#000');
rect.setAttribute('stroke-width','2');
rect.setAttribute('rx','7');

var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '10');
text.setAttribute('y', '20');
text.setAttribute('fill', '#000');
text.textContent = '2';

svg.appendChild(rect);
svg.appendChild(text); 

var wp = document.getElementById('wrapper'); 
wp.appendChild(svg);

这里是jsfiddle链接。 如果您检查SVG,您会看到文本元素的值,但浏览器不会呈现它。

谢谢。


1
我的猜测是,“动态地”在这里不是问题。 - John Dvorak
用户未展示“研究努力”。点赞,因为这是“如何向SVG图像添加动态文本”的完美参考?恭喜 ;) - bruno
4个回答

26

你的命名空间缺少一个“h”

过去式

var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text');

应该是这样的

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

2
是的!没错!我已经无数次地阅读过那段代码,但我没有注意到那个。非常感谢。 - and-k

12
    function createText() {

  var newText = document.createElementNS(svgNS,"text");
  newText.setAttributeNS(null,"x",20);      
  newText.setAttributeNS(null,"y",100);   
  var textNode = document.createTextNode("milind morey");
  newText.appendChild(textNode);
  document.getElementById("firstGroup").appendChild(newText);
}

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">    
       <g id="firstGroup">

    <text x="20" y="45" onclick="createText();" font-size=+13px">Click on this text to create a new text.</text>

  </g>
       </svg>

这仍然是最好的方式吗? - SuperUberDuper

0

我稍微压缩了一下你的代码,现在它可以工作了。

let txt='2';

wrapper.innerHTML=`
  <svg xlink="http://www.w3.org/1999/xlink" width="187" height="234">
    <rect width="187" height="234" fill="#fff" stroke="#000" 
          stroke-width="2" rx="7"></rect>
    <text x="10" y="20" fill="#000">${txt}</text>
  </svg>
`;
<div id=wrapper></div>


-1

你犯了一个非常简单的错误:

var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text'); ^^^ 相比之下

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); ^^^^ 打错了键盘!


你好,欢迎来到StackOverflow!这个问题已经有答案并且错别字已经被注意到了。不需要提交重复的答案。 - GKFX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接