添加延迟的jQuery

问题描述:

我用我的网站这个代码鼠标离开,我想知道我怎么能延迟添加到鼠标离开功能添加延迟的jQuery

$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)) 
       }) 

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

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

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

+0

谢谢你真棒,现在当我鼠标悬停另一个有没有办法我可以跳过那个超时? – 2010-09-14 14:16:10

+0

@Dustin - 是的,但我不能说没有看到你的'mouseenter'函数为其他元素,需要多一点上下文添加到问题。 – 2010-09-14 14:31:00

+0

我更新了代码,谢谢你的帮助 – 2010-09-14 14:38:19

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

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

我明白你的意思了,只是测试了第一个功能,它完全符合你所说的,你能帮忙吗?编辑我编辑过的帖子以进行您建议的更改? – 2010-09-14 14:37:53

+0

+1取消逻辑。我认为它可能应该是'$ target.one(“hover”,function()...'以在事件发生后摆脱事件。 – 2011-01-25 00:58:22

(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'); 

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

+0

完美工作。看起来像是我最好的解决方案:)很好地打包用于jQuery也是。竖起大拇指! – EinLama 2012-11-12 15:17:07

您可以使用此功能,我只是写:

$.fn.hoverDelay = function(handlerIn, handlerOut, delay) { 
    if(delay === undefined) delay = 400; 
    var timer; 
    this.hover(function(eventObject) { 
     clearTimeout(timer); 
     handlerIn.apply(this,eventObject); 
    }, function(eventObject) { 
     timer = setTimeout(handlerOut.bind(this, eventObject), delay); 
    }); 
}; 

它的工作原理就像正常$.hover除了有一个400毫秒的延迟之前的鼠标离开事件调用(如果在该时间范围内移回鼠标,则取消)。