How to show tooltip for text in SVG?

2019-06-20 05:14发布

I need a tooltip when the user hovers over text in SVG. Also, the text and the tooltip content should be modifiable with javascript.

The following works in Firefox but not Chrome. What's the correct way to do this?

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>

Javascript (with jQuery):

$('#text1').attr('title', 'Tooltip 1');
$('#text2').attr('title', 'Tooltip 2');

My jsfiddle: http://jsfiddle.net/getvictor/ctaVA/

2条回答
疯言疯语
2楼-- · 2019-06-20 05:31

A title child element will act as a tooltip.

<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>
查看更多
迷人小祖宗
3楼-- · 2019-06-20 05:32

You can use the <title> element.

Note that those implementations that do use <title> to display a tooltip often will only do so if the <title> is indeed the first child element of its parent.

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

So, in your example, that would be

<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>
   ...
查看更多
登录 后发表回答