2

我正在尝试仅使用css3和 html 做简单的工具提示,但转换不起作用。我究竟做错了什么?

HTML

<p>
    This has tooltip
</p>
<div class="tooltip">Tooltip content</div>

CSS

p {
    width: 200px;
    background-color: aqua;
    padding: 10px;
    margin-top: 50px;
}

div.tooltip {
    position: absolute;
    width: auto;
    padding: 10px;
    background-color: rgba(0,0,0, 0.5);
    top: 0px;
    display: none;
    opacity: 0.0;
    transition: opacity 1s;
    -webkit-transition: opacity 1s;
    -o-transition: opacity 1s;
    -moz-transition: opacity 1s;
}

p:hover + div.tooltip {
    display: block;
    opacity: 1.0;
    transition: opacity 1s;
    -webkit-transition: opacity 1s;
    -o-transition: opacity 1s;
    -moz-transition: opacity 1s;
}

http://jsfiddle.net/MCDg4/

4

2 回答 2

6

更新/替代解决方案

对于现代浏览器 CSS3 解决方案,您可以使用伪元素..

<span data-tooltip="I am the tooltip">This has a tooltip</span>

[data-tooltip]{
    position:relative;
}
[data-tooltip]:before{
    content:attr(data-tooltip);
    position:absolute;
    bottom:110%;
    padding:10px;
    background:#666;
    opacity:0;
    color:white;
    font-size:smaller;
    -webkit-transition:opacity 1s ease;
    -o-transition:opacity 1s ease;
    transition:opacity 1s ease;
    pointer-events:none;
}
[data-tooltip]:hover:before{
    opacity:1;
}

演示在 http://jsfiddle.net/BJ2tr/

这可以在没有伪元素的情况下通过将工具提示嵌套在它所引用的元素中并相应地调整 css 来完成


不幸的是,当您displaynone其他内容更改时,您无法进行转换。

而不是display:none你可以将它偏移到窗口之外(withtop:-9999px)并在显示它时将它带到位置。

div.tooltip {
    position: absolute;
    width: auto;
    padding: 10px;
    background-color: rgba(0,0,0, 0.5);
    top: -999px; /*CHANGED THIS AND REMOVED display:none*/
    display: none;
    opacity: 0.0;
    transition: opacity 1s;
    -webkit-transition: opacity 1s;
    -o-transition: opacity 1s;
    -moz-transition: opacity 1s;
}

p:hover + div.tooltip {
    opacity: 1.0;
    top: 0px; /*ADDED THIS AND REMOVED display:block*/
    transition: opacity 1s;
    -webkit-transition: opacity 1s;
    -o-transition: opacity 1s;
    -moz-transition: opacity 1s;
}

但是,这不会淡出(仅 in),因为它会在鼠标移出时将其移开(因此它实际上会淡出,但您看不到它,因为它在视口之外)..

于 2013-06-28T12:55:56.013 回答
5

解释

transition只穿上opacity,而当更改为display:block;它时,默认情况下显示为一个块opacity:1;

解决方案

(JSFiddle)

删除工具提示元素上的display:none;and 。display:block

于 2013-06-28T12:55:57.983 回答