2017-07-07 49 views
1

我爲SVG圖像(v2.0)呈現多行文本。每個文本行都被表示爲一個tspan元素。我遍歷所有tspans並將它們作爲新的子元素添加到文本元素(this.node)中。SVG的tspan的outerHTML替代方案

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

html輸出是一個單獨的字符串。

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

Firefox對於空間是嚴格的。所以,只要下一行以「i」(非常小的字符)開頭,瀏覽器就會在第一行的末尾呈現此char。它在用戶界面上看起來像「長長的texti」。

我的想法解決這個問題是在tspans之間添加一個空的空間。因此,Firefox呈現一個隱藏的僞空白字符(Example whitespace-only text nodes at Firefox's Dev tools

我試圖使用outerHTML屬性來設置一個空格。它在開發工具上工作(編輯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) 
} 

不幸的是,事實證明,outerHTML似乎是隻讀的。有人知道爲什麼嗎?有其他方法嗎?

+1

由於您正在使用HTML,請嘗試使用'innerHTML':'this.node.innerHTML + = tSpan.outerHTML +';'。 –

+0

@ibrahimmahrir thx,它的工作。作爲一個線路改變相當不錯。 –

+0

你甚至可以通過在一個變量中累加html來優化,然後只使用'innerHTML'('var html =「」; ... html + = tSpan.outerHTML +''; ... this.node.innerHTML = HTML;')。 (只調用一次'innerHTML'比多次調用它更好)。 –

回答

0

爲什麼不只是附加一個空間使用DOM給出這就是你正在做的附加tspans?

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