使用JQuery将工具提示相对于另一个div定位

8

这是我的工具提示标记和CSS:

<div class="tooltip">Click here to like it</div>

.tooltip {
    position: absolute;
    display: none;
    background: url('images/tooltip.gif') no-repeat;
    width: 100%;
    height: 40px;
    font-size: 0.8em;
    line-height: 40px;
    padding: 0px 0px 0px 8px;
}

现在,我的页面上有一个名为 #button_container 的 div。我想通过 JQuery 将这个 .tooltip div 放置在该 div 右侧 150 像素处。我知道需要设置此工具提示的 topleft 属性,但不确定如何操作。
理想情况下,工具提示的 top 属性应与 #button_container 相同(尽管 #button_container 没有被绝对定位),并且比 #button_containerleft 属性少 150 像素。
我不是很清楚如何开始这个操作,所以任何帮助都将不胜感激。谢谢。

我还想补充一点,我不太想添加任何外部库,比如提示库之类的。 - VIVA LA NWO
1个回答

6
首先建议您不要自己编写这个功能。有许多优秀的jQuery工具提示插件可供使用,只需选择一个即可。
除此之外,如果您想自己编写,有几种方法可以实现。其中一种是使用相对+绝对定位的CSS定位方法:
#button_container { position: relative; }
div.tooltip { position: absolute; top: 20px; right: 20px; }

这需要将工具提示放在按钮容器内。它的优点是,工具提示会随页面元素一起移动。

更常见的解决方案是使用类似以下内容的方法:

$("#button_container").hover(function(evt) {
  $("div.tooltip").css({top: evt.pageY + 10, left: evt.pageX + 10}).fadeIn();
}, function() {
  $("div.tooltip").fadeOut();
});

基本上,您可以在鼠标悬停在相关区域时将工具提示相对于鼠标移动。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接