【问题标题】:adding text with whitespaces in svg text element在 svg 文本元素中添加带空格的文本
【发布时间】: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


【解决方案1】:

您需要使用setAttributeNS 在 xml 命名空间中设置一个属性,所以在您的情况下...

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

如果在文本上设置了xml:space,则子 tspan 将使用该值,因此您无需再次设置它。

【讨论】:

  • 代码可以通过前缀4个空格来缩进,内联代码可以用周围的反引号标记:`Test` -> Test.
  • 非常感谢!你是天使! :D 虽然我必须将属性设置为 tspan 元素本身,但它现在可以工作了!
猜你喜欢
  • 2017-06-19
  • 2015-02-14
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多