我有一个 SVG,它在一个矩形 中包含文本。我想在某些用户交互时更改文本。
我遇到的大多数代码都是这样的:(示例代码用于添加圆圈)
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r", 20);
shape.setAttribute("fill", "green");
当我使用时:
function writeSVG() {
clearSVG();
var name = document.getElementById('txtName').value;
var txtNode = '<text id="newTxt" x="300" y="300">' + name + '</text>';
$('#svgElem').append(txtNode);
$('#popUp').hide();
}
//Removes all text from SVG rectangle
function clearSVG() {
$('#controls text').remove();
}
并且我的SVG直接写入了HTML
<div id="controls">
<svg id="svgElem" height="600" xmlns="http://www.w3.org/2000/svg" version="1.1"> Sorry, your browser does not support SVG.
<rect id="rectSVG" width="500" height="500" style="fill:#FFFFFF;stroke:black;stroke-width:2;" onclick="launchPopUp();" />
<text id="defaultTxt" x="200" y="200">Click in here!</text>
</svg>
</div>
注意:我使用的是 Safari 5.1
最佳答案
您创建 <text>
的方式元素将其放入错误的命名空间。创建一个字符串然后通过 .append() 解析它会将元素放入 HTML 命名空间,而不是 SVG 命名空间。
您必须将字符串包装在 <svg>
中和 </svg>
在解析之前,然后将结果根节点的子节点附加到您的 <svg>
DOM 中的元素。
关于javascript - 将元素动态添加到 SVG,元素添加到 HTML DOM 但未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13134818/