2017-02-12 8 views
0

Я пытаюсь добавить текст в элемент svg с javascript.Текст в 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 –