简体   繁体   English

SVG tspan的externalHTML替代

[英]outerHTML alternative for SVG's tspan

I'm rendering multiple lines of the text for an SVG image (v2.0). 我正在为SVG图像(v2.0)渲染多行文本。 Each text line is represented as one tspan element. 每行文字都表示为一个tspan元素。 I loop over all tspans and append them as new children to a text element (this.node). 我遍历所有tspan,并将它们作为新的子项附加到文本元素(this.node)。

while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
}

The html output is one single string. html输出是一个字符串。

<svg ...>
    <text ...>
        <tspan ...>Long text</tspan>
        <tspan ...>in the tspan</tspan>
    </text>
</svg>

Firefox is strict regarding the spaces. Firefox对空间要求严格。 So, whenever the next line starts with an "i" (very small char), the browser renders this char at the end of the first line. 因此,无论何时下一行以“ i”(非常小的字符)开头,浏览器都会在第一行的末尾呈现此字符。 It looks like "Long texti" at the UI. 在用户界面上看起来像“长文本”。

My idea to fix this was to add an empty space in between the tspans. 我要解决此问题的想法是在tspan之间添加一个空白区域。 So that Firefox renders a hidden pseudo whitespace character ( Example whitespace-only text nodes at Firefox's Dev tools ) 以便Firefox呈现隐藏的伪空白字符( Firefox的Dev工具中的仅空白文本节点示例

I tried to use the outerHTML property to set a blank space. 我试图使用externalHTML属性设置空白。 It's working at dev tools (Edit HTML). 它正在开发工具(编辑HTML)上运行。

<tspan ... />SPACE<tspan ... />

while (tSpans.length > 0) {
     var tSpan = tSpans.shift()

     console.log('before', tSpan.outerHTML)
     tSpan.outerHTML += ' '
     console.log('after', tSpan.outerHTML)

     this.node.appendChild(tSpan)
}

Sadly, it turns out that outerHTML seems to be read-only. 可悲的是,事实证明,outerHTML似乎是只读的。 Does somebody know why? 有人知道为什么吗? Is there an alternative way? 还有其他方法吗?

Why not just append a space using the DOM given that's what you're doing to append tspans? 考虑到要添加tspans,您为什么不使用DOM附加空格?

while (tSpans.length > 0) {
    var tSpan = tSpans.shift()
    this.node.appendChild(tSpan)
    this.node.appendChild(document.createTextNode(" "));
}

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

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