2010-09-14 135 views
5

我用我的網站這個代碼鼠標離開,我想知道我怎麼能延遲添加到鼠標離開功能添加延遲的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)) 
       }) 

回答

2

您可以使用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

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) 
}); 
+0

我明白你的意思了,只是測試了第一個功能,它完全符合你所說的,你能幫忙嗎?編輯我編輯過的帖子以進行您建議的更改? – 2010-09-14 14:37:53

+0

+1取消邏輯。我認爲它可能應該是'$ target.one(「hover」,function()...'以在事件發生後襬脫事件。 – 2011-01-25 00:58:22

4
(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

0

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

$.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毫秒的延遲之前的鼠標離開事件調用(如果在該時間範圍內移回鼠標,則取消)。