jQuery tool tip on hover

前端 未结 1 1778
花落未央
花落未央 2020-12-18 03:56

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 in

相关标签:
1条回答
  • 2020-12-18 04:27

    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.

    0 讨论(0)
提交回复
热议问题