这就是我所拥有的:
<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 在任何地方工作。
最佳答案
这不是 SVG 1.1 支持的东西。 SVG 1.2 确实有 textArea
元素,具有自动换行功能,但并非在所有浏览器中都实现了。 SVG 2 does not plan on implementing textArea
,但它确实有 auto-wrapped text 。
但是,如果您已经知道换行符应该出现在哪里,您可以将文本分成多个 <tspan>
,每个都使用 x="0"
和 dy="1.4em"
来模拟实际的文本行。例如:
<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 中。
关于javascript - 如何在 javascript 中换行 svg 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54573881/