鼠标悬停时 SVG 矩形显示 HTML 标题

SVG Rectangle display HTML title on mouseover

我尝试在鼠标悬停在矩形上时显示工具提示。我的尝试是使用 <g> 并为其设置 title 并将 title 设置为 <rect> 本身,但不会产生任何可见输出(on Chrome).

HTML

<svg width="200px" height="200px">
  <g title="blue rectangle">
    <rect width="50px" height="50px" fill="blue" x="10px" y="10px"></rect>
  </g>
  <rect width="50px" height="50px" fill="red" x="60px" y="60px" title="red rectangle"></rect>
</svg>

JSFiddle

观察

感谢 @Jacob Gray 的评论,问题仍然存在于 Chrome(FireFox 行为正确)。

谁能给我指出正确的方向?

有两种方法:使用推荐的<title></title>元素和不推荐的title属性

不鼓励在 W3C spec 中使用 title 属性 。它甚至带有警告。

Warning!

Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).


然而,正如 this answer by Phrogz 中提到的,SVG 实际上有一个元素。

MDN: SVG <title> 元素

Each container element or graphics element in an SVG drawing can supply a title description string where the description is text-only. When the current SVG document fragment is rendered as SVG on visual media, title element is not rendered as part of the graphics. However, some user agents may, for example, display the title element as a tooltip. Alternate presentations are possible, both visual and aural, which display the title element but do not display path elements or other graphics elements. The title element generally improve accessibility of SVG documents

W3C SVG Spec <desc> & <title> 元素

<svg width="200px" height="200px">
  <g>
    <title>blue rectangle</title>
    <rect width="50px" height="50px" fill="blue" x="10px" y="10px"></rect>

  </g>
  <rect width="50px" height="50px" fill="red" x="60px" y="60px" title="red rectangle"></rect>
</svg>

我已经修复了 Firefox from version 46 中 SVG 元素的 title 属性的错误显示问题。

Chrome 和 Firefox 现在的行为相同,它们都需要用于 SVG 工具提示的子 <title> 元素。请注意,那里没有任何变化,两个 UA 现在已经在许多版本中以这种方式工作。