我正在通过 JavaScript 创建 SVG 元素,它工作正常,但是当我创建一个文本 SVG 元素并定义它的内容时,浏览器只是不呈现该值,尽管当我检查它时该值在代码中用 Firebug 。
代码是:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xlink','http://www.w3.org/1999/xlink');
svg.setAttribute('width','187');
svg.setAttribute('height','234');
var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('width','187');
rect.setAttribute('height','234');
rect.setAttribute('fill','#fff');
rect.setAttribute('stroke','#000');
rect.setAttribute('stroke-width','2');
rect.setAttribute('rx','7');
var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '10');
text.setAttribute('y', '20');
text.setAttribute('fill', '#000');
text.textContent = '2';
svg.appendChild(rect);
svg.appendChild(text);
var wp = document.getElementById('wrapper');
wp.appendChild(svg);
这是 jsfiddle link . 如果您检查 SVG,您会在那里看到文本元素的值,但浏览器不会呈现它。
谢谢
最佳答案
你的命名空间中少了一个“h”
是
var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text');
应该是
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
关于javascript - 通过javascript动态设置文本SVG元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758125/