如何在SVG中显示文本的工具提示?

Vic*_*sky 7 javascript svg tooltip

当用户将鼠标悬停在SVG中的文本上时,我需要一个工具提示.此外,文本和工具提示内容应该可以使用javascript进行修改.

以下适用于Firefox,但不适用于Chrome.这样做的正确方法是什么?

HTML:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100" height="100">
    <rect width="100" height="100" style="fill:black;stroke-width:0"></rect>
    <text id="text1" x="50" y="15" text-anchor="end">text1</text>
    <text id="text2" x="80" y="15" text-anchor="end"
      transform="translate(0,50)">text2</text>
</svg>
Run Code Online (Sandbox Code Playgroud)

Javascript(使用jQuery):

$('#text1').attr('title', 'Tooltip 1');
$('#text2').attr('title', 'Tooltip 2');
Run Code Online (Sandbox Code Playgroud)

我的jsfiddle:http://jsfiddle.net/getvictor/ctaVA/

Rob*_*son 20

标题子元素将充当工具提示.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100" height="100">
    <rect width="100" height="100" style="fill:black;stroke-width:0"></rect>
    <text id="text1" x="50" y="15" text-anchor="end"><title>Tooltip 1</title>text1</text>
    <text id="text2" x="80" y="15" text-anchor="end"
      transform="translate(0,50)"><title>Tooltip 2</title>text2</text>
</svg>
Run Code Online (Sandbox Code Playgroud)


Ter*_*den 5

您可以使用该<title>元素。

请注意,那些确实用于<title>显示工具提示的实现通常只有在<title>确实是其父元素第一个子元素时才会这样做。

来自https://developer.mozilla.org/en/docs/Web/SVG/Element/title

所以,在你的例子中,那就是

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100" height="100">
   <title id="title1">This is a tooltip</title>
   <rect width="100" height="100" style="fill:black;stroke-width:0"></rect>
   ...
Run Code Online (Sandbox Code Playgroud)