SVG使用元素工具提示

时间:2016-04-26 04:40:33

标签: javascript css svg tooltip

使用现代浏览器,是否可以让< use >元素在鼠标悬停时显示rect工具提示?

15.2.1 The hint element指定。

<svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <symbol id="pnp-transistor">
        <image xlink:href="transistor.png" height="32px" width="32px" />

        <rect y="0" x="0" height="6px" width="32px">
            <title>collector</title>
            <hint>collector</hint>
        </rect>

        <rect y="27" x="0" height="6px" width="32px">
            <title>emitter</title>
            <hint>emitter</hint>
        </rect>

        <rect y="0" x="0" height="32px" width="6px">
            <title>base</title>
            <hint>base</hint>
        </rect>
    </symbol>

    <use xlink:href="#pnp-transistor"></use>
</svg>

1 个答案:

答案 0 :(得分:0)

没有JavaScript,似乎没有办法做到这一点,使用getBoundingClientRect()来定位SVG在DOM中的位置。好东西在这里:How to add a tooltip to an svg graphic。即使在那时,我也不确定这个方向的支持和容易程度。

但是,一种可能的解决方法是在符号上添加另一个包装器,并在将鼠标悬停在伪类上时将CSS绑定到其中。使用attr(data-tooltip)并不像使用符号直接继承的内容那样好,但它并不是一个可怕的第二位。

例如:

<div class="wrapper" data-tooltip="SVG Tooltip (almost)">
  <svg class="icon"><use xlink:href="#some-id"></use></svg>  
</div>

...

.wrapper:after {
  position: absolute;
  left: 50%;
  transition: 0.5s;
  content: attr(data-tooltip);
  white-space: nowrap;
  opacity: 0;
  font-size: 1.5rem;
  transform: translate(-50%, 0);
}

.wrapper:hover:after {
  position: absolute;
  opacity: 1;
  transform: translate(-50%, 0.5em);
}

enter image description here

Codepen:SVG With Pure CSS Tooltip