通过javascript动态设置文本svg元素

and*_*d-k 28 javascript svg

我正在通过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);
Run Code Online (Sandbox Code Playgroud)

这里是jsfiddle链接http://jsfiddle.net/sAhyC/ 如果您检查svg,您将看到文本元素的值,但浏览器不会呈现它.

谢谢

cmo*_*key 17

你在命名空间中缩短了"h"

var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text');
Run Code Online (Sandbox Code Playgroud)

应该

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
Run Code Online (Sandbox Code Playgroud)

  • 是的!这是正确的!我已经无数次阅读该代码,但我没有注意到。非常感谢你 (2认同)

小智 7

    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);
}
Run Code Online (Sandbox Code Playgroud)
 <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>
Run Code Online (Sandbox Code Playgroud)