在jquery中为mouseleave添加延迟

Dus*_*thy 5 jquery

我在我的网站中使用此代码,我想知道如何为mouseleave函数添加延迟

$target.mouseenter(function(e){
                var $tooltip=$("#"+this._tipid)
                ddimgtooltip.showbox($, $tooltip, e)
            })
            $target.mouseleave(function(e){
             var $tooltip=$("#"+this._tipid);
             setTimeout(function() { ddimgtooltip.hidebox($, $tooltip); }, 4000);
            })

            $target.mousemove(function(e){
                var $tooltip=$("#"+this._tipid)
                ddimgtooltip.positiontooltip($, $tooltip, e)
            })
            if ($tooltip){ //add mouseenter to this tooltip (only if event hasn't already been added)
                $tooltip.mouseenter(function(){
                    ddimgtooltip.hidebox($, $(this))
                })
Run Code Online (Sandbox Code Playgroud)

CBa*_*arr 10

只有一个计时器的问题是如果你向左鼠标然后重新输入它仍然会在该计时器完成后隐藏.像下面这样的东西可能会更好,因为我们可以在鼠标进入目标时取消计时器.

var myTimer=false;
$target.hover(function(){
    //mouse enter
    clearTimeout(myTimer);
},
function(){
    //mouse leave
    var $tooltip=$("#"+this._tipid);
    myTimer = setTimeout(function(){
        ddimgtooltip.hidebox($, $tooltip);
    },500)
});
Run Code Online (Sandbox Code Playgroud)


ide*_*awu 5

(function($){
   $.fn.lazybind = function(event, fn, timeout, abort){
        var timer = null;
        $(this).bind(event, function(){
            timer = setTimeout(fn, timeout);
        });
        if(abort == undefined){
            return;
        }
        $(this).bind(abort, function(){
            if(timer != null){
                clearTimeout(timer);
            }
        });
    };
})(jQuery);


$('#tooltip').lazybind(
    'mouseout',
    function(){
        $('#tooltip').hide();
    },
    540,
    'mouseover');
Run Code Online (Sandbox Code Playgroud)

http://www.ideawu.com/blog/2011/05/jquery-delay-bind-event-handler-lazy-bind.html


Nic*_*ver 2

您可以setTimeout()为此使用匿名函数:

$target.mouseleave(function(e){
 var $tooltip=$("#"+this._tipid);
 setTimeout(function() { ddimgtooltip.hidebox($, $tooltip); }, 250);
})
Run Code Online (Sandbox Code Playgroud)

这会在离开后延迟 250 毫秒才隐藏,您可以根据需要调整该值。