通过javascript动态设置文本SVG元素
我是通过JavaScript创建SVG元素的,它工作得很好,但是当我创建一个文本SVG元素并定义它的内容时,浏览器不会呈现该值,尽管当我使用firebug检查它时,该值在代码中 代码是:通过javascript动态设置文本SVG元素,javascript,svg,Javascript,Svg,我是通过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',
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);
这是你的电话号码。
如果检查SVG,您将在那里看到文本元素的值,但浏览器不会呈现它
谢谢您的命名空间中缺少一个“h”
是
应该是
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
我把你的代码压缩了一点,现在可以了
let txt='2';
wrapper.innerHTML=`
${txt}
`;代码>
您犯了一个非常简单的错误:
var text=document.createElements('ttp://www.w3.org/2000/svg","文本",;
^^^
相比
var text=document.createElements(“”,'text');
^^^^
按键盘 我的猜测是,“动态”不是这里的问题。用户未能显示“研究努力”。Upvoting,因为这是“如何将动态文本添加到svg图像”的完美参考是 啊这是正确的!我已经读过无数次了,但是我没有注意到。非常感谢大家您好,欢迎来到StackOverflow!这个问题已经得到了回答,打字错误也被注意到了。没有必要提交重复的答案。这仍然是最好的方式吗?
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
function createText() {
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",20);
newText.setAttributeNS(null,"y",100);
var textNode = document.createTextNode("milind morey");
newText.appendChild(textNode);
document.getElementById("firstGroup").appendChild(newText);
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
<g id="firstGroup">
<text x="20" y="45" onclick="createText();" font-size=+13px">Click on this text to create a new text.</text>
</g>
</svg>