如何在 javascript 中对 svg 文本进行换行? [英] How to linebreak an svg text within javascript?

查看:27
本文介绍了如何在 javascript 中对 svg 文本进行换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

<path class="..." onmousemove="show_tooltip(event,'very long text 
    \
 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>,每个带有 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆