Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - jQuery tool tip on hover

I am in need of a very lightweight tooltip similar to the 1 found here http://www.history.com/videos when you hover a video link under "Popular Videos", a tooltip fades into place, it stays there and you can even select text on it until you move the cursor off it. Facebook and Google+ also have a similar style tool-tip as well as stackoverflow when you hover over a tag. Can someone provide a light weight method of doing this.

I have search and looked at many existing "plugins" they are all somewhat bloated though. Thanks for any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a pretty simple way you could accomplish this:

var timeout;

function hide() {
    timeout = setTimeout(function () {
        $("#tooltip").hide('fast');
    }, 500);
};

$("#tip").mouseover(function () {
    clearTimeout(timeout);
    $("#tooltip").stop().show('fast');
}).mouseout(hide);

$("#tooltip").mouseover(function () {
    clearTimeout(timeout);
}).mouseout(hide);

Where #tip is the element you want to mouseover to make the tooltip appear, and #tooltip is the actual tooltip element.

Here's an example: http://jsfiddle.net/pvyhY/


If you wanted to wrap this in a jQuery plugin:

(function($) {
    $.fn.tooltip = function(tooltipEl) {
        var $tooltipEl = $(tooltipEl);
        return this.each(function() {
            var $this = $(this);            
            var hide = function () {
                var timeout = setTimeout(function () {
                    $tooltipEl.hide();
                }, 500);

                $this.data("tooltip.timeout", timeout);
            };

            /* Bind an event handler to 'hover' (mouseover/mouseout): */
            $this.hover(function () {
                clearTimeout($this.data("tooltip.timeout"));
                $tooltipEl.show();
            }, hide);

            /* If the user is hovering over the tooltip div, cancel the timeout: */
            $tooltipEl.hover(function () {
                clearTimeout($this.data("tooltip.timeout"));
            }, hide);            
        });
    };
})(jQuery);

Usage:

$(document).ready(function() {
    $("#tip").tooltip("#tooltip");
});

Add more functionality and you'll eventually end up with the excellent qTip plugin, which I recommend taking a look at as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...