jQuery:如何在没有链接的情况下显示工具提示

4

是否可以在没有链接的情况下显示工具提示?

例如,我有以下没有链接的代码:

<ul class="letters" title="This is the title">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>

那么我应该如何在鼠标悬停时显示提示 "This is the title" 呢?
顺便说一下,我不想使用任何工具提示插件。
2个回答

5

你说不想利用其他人已经完成的工作,这会让你的生活变得更加艰难。 :-)

以下是一些组成部分:

  • You can find all of the ul elements that have a title attribute via $ or jQuery:

    var targets = $("ul[title]");
    
  • You can watch them for the mouseenter event and, if no mouseleave event fires within X milliseconds, show your tooltip. (These are IE-specific events, but jQuery provides them on all browsers, which is very helpful. It also provides hover, which is just a convenience means of hooking up mouseenter and mouseleave handlers.) Although this means you're hooking up a lot of event handlers (since mouseenter and mouseleave don't bubble — part of what makes them so handy). You may well be better off tracking mouseover/mouseout at the document level and handling the complexities that arise, since they do bubble.

  • To show your tooltip, you can get the location of the element in question (via offset) and show an absolutely-positioned div nearby containing the title (which you can get via attr).

  • When the user moves the mouse out of the tooltip (mouseleave), remove it.

但是,你可能考虑使用已经完成这项工作的项目中的代码,找到所有的问题等。首先阅读代码以确保它正在做你想要的事情而不是你不想要的事情,但重新发明轮子通常(并非总是!)是浪费时间的……即使你最终没有使用插件,阅读并了解其中的陷阱可能也是有用的。


1

获取标题属性

title = $('.letters').attr('title');

从那里开始工作。在Jquery中没有神奇的"title_tooltip_popup()"函数,所以你可以考虑制作自己的函数或使用插件。


请记住,如果您正在使用类,这个选择器

$('.letters')

可能引用多个元素


$('.letters').hover(function(){ title = $(this).attr('title'); }); - Ben

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