Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

javascript - Display Text Over SVG Element On Hover

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>

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...