如何在javascript中换行svg文本? [英] How to linebreak an svg text within javascript?
问题描述
所以这就是我所拥有的:
So here is what I have:
<path class="..." onmousemove="show_tooltip(event,'very long text
\\\n I would like to linebreak')" onmouseout="hide_tooltip()" d="..."/>
<rect class="tooltip_bg" id="tooltip_bg" ... />
<text class="tooltip" id="tooltip" ...>Tooltip</text>
<script>
<![CDATA[
function show_tooltip(e,text) {
var tt = document.getElementById('tooltip');
var bg = document.getElementById('tooltip_bg');
// set position ...
tt.textContent=text;
bg.setAttribute('width',tt.getBBox().width+10);
bg.setAttribute('height',tt.getBBox().height+6);
// set visibility ...
}
...
现在我很长的工具提示文本没有换行符,即使我使用alert();它告诉我,文本实际上有两行。 (它包含一个\但是,如何删除那个?)
我无法让CDATA在任何地方工作。
Now my very long tooltip text doesn't have a linebreak, even though if I use alert(); it shows me that the text actually DOES have two lines. (It contains a "\" though, how do I remove that one by the way?)
I can't get CDATA to work anywhere.
推荐答案
这不是SVG 1.1支持的。 SVG 1.2确实有 textArea
元素,带有自动换行功能,但并未在所有浏览器中实现。 SVG 2 不打算实施 textArea
,但确实有自动换行的文字。
This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea
element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea
, but it does have auto-wrapped text.
但是,鉴于您已经知道您的换行符应该发生在哪里,您可以将文本分成多个< tspan>
s,每个 $ c> x =0和 dy =1.4em
来模拟实际的文本行。例如:
However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>
s, each with x="0"
and dy="1.4em"
to simulate actual lines of text. For example:
<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
<text x="0" y="0">
<tspan x="0" dy="1.2em">very long text</tspan>
<tspan x="0" dy="1.2em">I would like to linebreak</tspan>
</text>
</g>
当然,既然你想用JavaScript做到这一点,你就必须手动创建和插入每个元素都进入DOM。
Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.
这篇关于如何在javascript中换行svg文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!