【发布时间】:2023-03-20 20:00:02
【问题描述】:
我正在尝试将一些包含多个空格的文本添加到 svg 文本元素。我完全绝望,因为当一个接一个以上的空格时,它们被正确添加到元素中,但不会显示在浏览器窗口中。
这里的这个人在文本元素中使用了空格,当我静态复制它时效果很好,但是当用 js 添加文本时,空格消失了!
Significant whitespace in SVG embedded in HTML
如何将带空格的文本动态添加到 svg?
感谢任何答案!
var legend = document.createElementNS("http://www.w3.org/2000/svg", "text");
var tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
// Set any attributes as desired
legend.setAttribute("id","legend");
legend.setAttribute("text-anchor", "middle");
legend.setAttribute("alignment-baseline", "hanging");
legend.setAttribute("xml:space","preserve");
tspan.setAttribute("xml:space","preserve");
tspan.setAttribute("id","tspanObj");
var myText = document.createTextNode(legendTxt);
tspan.appendChild(myText);
legend.appendChild(tspan);
legend.setAttribute("x", Math.round(this.options.windowWidth/2));
legend.setAttribute("y", this.options.upperPadding+this.options.barH+this.options.legendDist);
this.elements.jSvgElem.append(legend);
【问题讨论】:
-
如您所见,我什至将 xml:space="preserve" 设置为 svg
元素和 ...然后将 textnode 附加到 tspan,将 tspan 附加到文本元素和这个到svg ...但是...仍然连续的空格被消除...fuuuuuuuuuuuuu
标签: javascript text svg whitespace textnode