开发者

Positioning a tooltip relative to another div in JQuery

Here's my tooltips markup and 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;
}

Now, I have a div on my page called #button_container. I would like to place this .tooltip div 150px to the right of that div via JQuery. I understand I need to set this tooltips top and left attributes, but not sure how.

Idealy the tooltips top attribute should be the same as #button_cont开发者_如何学Cainer (although #button_container isn't positioned absolutely) and 150 less than #button_container's left attribute.

I don't really know where to get started on this so any help would be very much appreciated. Thanks.


Firstly a piece of advice: don't roll your own on this. There are many excellent jQuery tooltip plugins. Just use one of them.

That aside, if you want to go down this route, there are a couple of ways of doing it. The CSS positioning route is to use relative+absolute positioning:

#button_container { position: relative; }
div.tooltip { position: absolute; top: 20px; right: 20px; }

This requires the tooltip to be inside the button container. It has the advantage that the tooltip will move with the rest of the page elements.

The more common solution is to use something like:

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

Basically you move the tooltip relative to the mouse while over the relevant region.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜