如何在SVG文本中保留空格

use*_*754 4 svg snap.svg

为了在svg的textelement中保留空格,应使用'xml:space =“ preserve”'作为文本(jsfiddle)的属性。但是,它不起作用。我究竟做错了什么?

    // init snap
    var svgElement=document.getElementById("mainSvgId");
    var s = Snap(svgElement).attr({height: 300, width: 300});

    // greate group with rectanle
    var parentGroup=s.g().attr({id: "parent"});
    var rect1 = s.rect(0, 0, 200, 200).attr({fill: "#bada55"});
    parentGroup.add(rect1);

    // add text with preserve attribute
    var text = s.text(0, 20, "   text1    text2");
    text.node.setAttribute("xml:space", "preserve");
    parentGroup.add(text);
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 5

你快到了。您需要在需要setAttributeNS而不是setAttribute的xml命名空间中正确创建属性。

text.node.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve");
Run Code Online (Sandbox Code Playgroud)

  • 这显然是[已弃用](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xml:space)。您现在应该使用 [CSS 空白](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)。 (3认同)