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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19637443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:17:25  来源:igfitidea点击:

How to show tooltip for text in SVG?

javascriptsvgtooltip

提问by Victor Lyuboslavsky

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

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

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

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

HTML:

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):

Javascript(使用 jQuery):

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

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

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

回答by Robert Longson

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>

回答by Terence Eden

You can use the <title>element.

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

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 elementof its parent.

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

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

来自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>
   ...