【问题标题】:Adding tooltip to SVG rect tag将工具提示添加到 SVG rect 标签
【发布时间】:2015-03-22 14:02:36
【问题描述】:

将工具提示添加到<rect> 的最佳解决方案是什么?

我创建了带有多个 <rect> 标记的 SVG 地图,我想在鼠标悬停时显示工具提示。使用 title 属性很好,但是有没有办法使用 CSS/Javascript/jQuery 重新设置它的样式,或者有没有更好的选项来添加工具提示?

<svg version="1.1" baseProfile="basic" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" xml:space="preserve">
    <g>
        <rect id="1" title="There's some text" x="0" y="0" fill="#666666" width="20" height="20"/>
        <rect id="2" title="There's another text" x="30" y="0" fill="#666666" width="20" height="20"/>
    </g>
</svg>

【问题讨论】:

    标签: html css svg tooltip title


    【解决方案1】:

    SVG 使用标题元素,而不是属性,但是您不能 为它们设置样式。如果您需要样式,则需要将标题动态创建为 &lt;text&gt; 元素并使用 javascript 将其放置在正确的位置。

    这是默认工具提示的样子...

    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" xml:space="preserve">
        <g>
            <rect id="1" fill="#666666" width="20" height="20">
              <title>There's some text</title>
            </rect>
            <rect id="2" x="30" fill="#666666" width="20" height="20">
              <title>There's another text</title>
            </rect>
       </g>
    </svg>

    【讨论】:

    • 谢谢。那么我应该如何设置这些&lt;title&gt; 标签的样式呢?
    • 这是不可能的,你需要自己动手,正如我在回答中已经说过的那样。
    【解决方案2】:

    我尝试了您的代码,但它不起作用(Chrome)。然后我在这个网站上发现了一篇关于工具提示的帖子:

    How to add a tooltip to an svg graphic?

    所以不要添加title属性,你需要这样做:

    <rect id="1" x="0" y="0" fill="#666666" width="20" height="20"><title>"There's some text"</title/></rect>
    

    更新

    您可以使用 javascript 和 jquery 更改文本和样式

    例子:

    $("#1").find("title").html("Text") 
    

    【讨论】:

    • 谢谢。但是有什么方法可以设置这些样式吗?
    • 还可以查看这篇关于 css 原生工具提示的帖子:stackoverflow.com/questions/9927640/…
    • 您可以更改标题的 html 但样式不起作用:$("#1").find("title").css("color", "red")
    • 无论如何感谢您的帮助。这可能不是正确的解决方案。我想我得为此使用一些插件。
    • 您无法设置默认工具提示的样式,但上一个链接显示了另一种选择。
    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 2018-12-28
    • 2018-01-20
    • 1970-01-01
    • 2019-11-25
    • 2014-03-19
    • 1970-01-01
    相关资源
    最近更新 更多