30

我正在通过 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,您将在那里看到文本元素的值,但浏览器不会呈现它。

谢谢

4

4 回答 4

22

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

曾是

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

应该

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
于 2013-02-07T18:26:21.257 回答
10
    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>
于 2014-06-02T06:42:48.460 回答
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>

于 2019-05-21T13:57:37.960 回答
-1

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

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

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

于 2020-05-13T20:05:00.897 回答