zea*_*uss 16 javascript jquery svg
我正在尝试<g>使用javascript 将文本元素添加到SVG文档中的元素,我的代码如下所示
function addText(x,y,val){
var newtxt = document.createElementNS("http://www.w3.org/2000/svg", "text");
$newtxt = $(newtxt);
$newtxt.attr('x',x);
$newtxt.attr('y',y);
$newtxt.attr('font-size','100');
$newtxt.val(val);
$newtxt.appendTo($('g'));}
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,文本没有显示.元素被添加到<g>元素,但值没有设置..任何想法如何解决这个?
Bil*_*ill 46
我认为您需要创建一个文本节点来保存字符串并将其附加到SVG文本元素.
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",x);
newText.setAttributeNS(null,"y",y);
newText.setAttributeNS(null,"font-size","100");
var textNode = document.createTextNode(val);
newText.appendChild(textNode);
document.getElementById("g").appendChild(newText);
Run Code Online (Sandbox Code Playgroud)
在http://www.carto.net/svg/manipulating_svg_with_dom_ecmascript/上有一个工作示例.
小智 5
var txt = document.createElementNS(svgNS, 'text');
txt.setAttributeNS(null, 'x', x);
txt.setAttributeNS(null, 'y', y);
txt.setAttributeNS(null,'font-size','100');
txt.innerHTML = val;
document.getElementById("g").appendChild(txt);
Run Code Online (Sandbox Code Playgroud)