2017-02-12 45 views
0

我试图用javascript将文本添加到svg元素。SVG中的文本不会出现

这里是我的javascript代码:

var svg=document.getElementById("svgtext"); 
var newText = document.createElementNS(svg,"text"); 
newText.setAttributeNS(null,"x",0);  
newText.setAttributeNS(null,"y",50); 
newText.setAttributeNS(null,"font-size","100"); 
newText.setAttributeNS(null,"fill","black"); 
var textNode = document.createTextNode("Hello World"); 
newText.appendChild(textNode); 
document.getElementById("gText").appendChild(newText); 

,这是HTML

  <svg id="svgtext" width=160px height=250px> 
       <g id="gText"> 
        <text x="0" y="15" fill="black">SVG!</text> 
       </g> 
     </svg> 

正如你可以看到,如果我手动添加一些文字,它完美的作品。当我尝试使用JavaScript时,我可以看到它出现在Chrome的检查器工具中,但它不会显示在屏幕上。

回答

0

您正在将错误值传递给createElementNS的第一个参数。它应该是为below.§

var newText = document.createElementNS("http://www.w3.org/2000/svg", "text"); 
 
newText.setAttributeNS(null,"x",0);  
 
newText.setAttributeNS(null,"y",50); 
 
newText.setAttributeNS(null,"font-size","100"); 
 
newText.setAttributeNS(null,"fill","black"); 
 
var textNode = document.createTextNode("Hello World"); 
 
newText.appendChild(textNode); 
 
document.getElementById("gText").appendChild(newText);
  <svg id="svgtext" width="160px" height="250px"> 
 
       <g id="gText"> 
 
        <text x="0" y="15" fill="black">SVG!</text> 
 
       </g> 
 
     </svg>

+0

这是正确的,非常感谢你:d –