[英]Text in SVG does not appear
我正在嘗試使用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的檢查器工具中看到它,但是它沒有出現在屏幕上。
您將錯誤的值傳遞給createElementNS的第一個參數。 它應該如下所示。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.