2017-02-12 46 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 –