简体   繁体   English

在svg文本元素中添加带有空格的文本

[英]adding text with whitespaces in svg text element

Im trying to add some text that contains several whitespaces to a svg text element. 我试图添加一些包含几个空格的文本到svg文本元素。 I'm totally desprate, because when there is more than one whitespaces after an other they are added correctly to the element but do not show up in the browser window. 我完全不屑一顾,因为当有一个以上的空格后,它们被正确地添加到元素中但不会显示在浏览器窗口中。

This guy here uses whitespaces in the text element and it works fine when i reproduce it static, but when adding the text with js the whitespaces disappear! 这个人在这里使用文本元素中的空格,当我将其重现为静态时它工作正常,但是当用js添加文本时,空格会消失!

Significant whitespace in SVG embedded in HTML 嵌入在HTML中的SVG中的重要空白

How can i add text with whitespaces dynamically to a svg? 如何将带有空格的文本动态添加到svg?

Thx for any answer! 谢谢任何答案!

    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);

You need to use setAttributeNS to set an attribute in the xml namespace so in your case... 您需要使用setAttributeNS在xml命名空间中设置属性,以便在您的情况下...

legend.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");

If xml:space is set on the text, the child tspan will use that value so you don't need to set it again in your case. 如果在文本上设置了xml:space ,则子tspan将使用该值,因此您不需要在您的情况下再次设置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM