如何在没有插件的情况下使用jquery创建工具提示?

问题描述:

这些年来,我使用了几种不同的工具提示插件,但我认为现在该是编写自己的工具的时候了.简而言之,我并不是在寻找具有所有选项的插件,因为我知道我希望每个弹出的工具提示都具有外观和行为.大多数插件都有一系列可用的动画和位置,我想在我的帮助下,当然,对于我想创建的轻量级插件来说,这是多余的:)

I have used a few different tooltip plugins over the years, but I think its become time to write my own. Simply, I'm not looking for a plugin which has all the options, as I know how I want every tooltip that pops up to look and behave. Most plugins have a range of animation and positions available and I think thats excessive for the lightweight one I'm wanting to create, with your help of course :)

基本上,使用悬停的title属性,我希望工具提示直接出现在悬停的元素上方并居中.

Basically, using the title attribute of the hover, I want a tooltip to appear directly above and centered to the element being hovered.

我知道如何填充将显示的div,但是我要尝试的工作是如何告诉div将自身直接定位在元素上方.

I know how to populate the div that will be shown, but what I'm trying to work out, is how to tell that div to position itself directly above the element.

理想情况下,这是使用最少的代码完成的.我的逻辑说像这样(伪代码):

ideally this is done with minimal code. My logic says something like this (pseudo code):

<html>
<head>

<style type="text/css">

    #myToolTip { display: none; }

</style>

<script type="text/javascript">

$(document).ready(function() {

    $('.hoverAble').hover(function(){

        var tip = $(this).attr('title');

        $('#myToolTip').html(tip).fadeIn();

    }, function() {

        $('#myToolTip').fadeOut();

    }

});
</script>
</head>
<body>

<div id="myToolTip"></div>

<div class="hoverAble" title="I am good at code"></div>

</body>
</html>

当然,以上代码仅用于填充工具提示,而不是相对于悬停的元素定位.那就是我的理解力不足的地方.你能帮忙吗?

of course the above code is just going to fill the tooltip and not be positioned relative to the hovered element. Thats where my understanding falls short. Can you help?

编辑:为了澄清起见,我不希望工具提示随鼠标移动.

Just for clarification, i'm not wanting the tooltip to move with the mouse.

看看各种 CSS函数在jQuery中,主要是 offset() ,也许还有

Take a look at the various CSS functions in jQuery, mostly offset() and maybe height().

// pseudocode, assuming #tooltip has position: absolute
// do something similar with the left offset as well
$('#tooltip').css({ top : $('#link').offset().top + 10 + 'px' });

这会将工具提示静态地放置在链接之上或附近,我认为这是您想要的.如果要用鼠标移动工具提示,则需要动态更新 mousemove中的位置事件.

This would place the tooltip statically over, or close to, the link, which I think is what you're looking for. If you want the tooltip to move with the mouse, you'll need to dynamically update the position in a mousemove event.