在悬停时通过SVG元素显示文本 [英] Display Text Over SVG Element On Hover

查看:731
本文介绍了在悬停时通过SVG元素显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个简单的SVG元素(在下面复制),并且当将具有bar类的矩形悬停在上方时,我想显示文本(当前在data-label属性内).

So I have a simple SVG element (copied below), and I want to display text (currently within the data-label attribute) when the rectangle with the bar class is hovered over.

<svg width="511" height="15">
    <rect fill="#555555" height="15" stroke="#000000" width="510"></rect>
    <rect class="bar" x="2" y="2" width="434" height="11" fill="#97C115" data-label="Test-Label"></rect>
</svg>

SVG中可以有任意数量的矩形,并且标签可以显示任何内容.

There could be any number of rectangles in the SVG and the label could say anything.

由于我的情况,整个SVG元素都是用JavaScript创建的,然后打印到HTML环境中,因此我可以将标签移动到任何地方.我只希望标签在悬停时显示在矩形上方或上方.

Since in my situation, the entire SVG element is created in JavaScript and then printed to a HTML environment, I am able to move the label anywhere. I just want the label to appear over the rectangle or above it when hovered.

这是不可能的,因为您不能在<rect>元素内包含文本吗?

Is this at all possible, since you cannot include text within the <rect> element?

推荐答案

是这样的吗?您可以使用g对元素进行分组.

Something like this? You can use g to group elements.

svg text {display: none;}
svg g:hover text {display: block;}

<svg width="511" height="15">
    <rect fill="#555555" height="15" stroke="#000000" width="510"></rect>
    <g>
      <rect class="bar" x="2" y="2" width="434" height="11" fill="#97C115" data-label="Test-Label"></rect>
      <text x="0" y="15">Label 1</text>
    </g>
</svg>

这篇关于在悬停时通过SVG元素显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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