在javascript中将文本添加到SVG文档

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/上有一个工作示例.

  • 我想知道为什么他们真的这么复杂 (3认同)
  • Bill 可以更新它指向 404 页面的链接吗? (2认同)

小智 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)

  • 虽然此代码片段可能会解决问题,但 [包括解释](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您提出代码建议的原因。也请尽量不要在您的代码中添加解释性注释,因为这会降低代码和解释的可读性! (2认同)