Add delay to mouseleave in jquery

后端 未结 4 1823
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 04:07

I\'m using this code in my site and I was wondering how I could add a delay to the mouseleave function

$target.mouseenter(function(e){
                var $t         


        
相关标签:
4条回答
  • 2021-01-13 04:56

    The problem with just a timer would be if you mouse left and then re-entered it would still hide after that timer completed. Something like the following might work better because we can cancel the timer whenever the mouse enters the target.

    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 讨论(0)
  • 2021-01-13 04:56

    You can use setTimeout() and an anonymous function for this:

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

    This would delay it 250ms after leaving before it hides, you can just adjust that value as needed.

    0 讨论(0)
  • 2021-01-13 04:59

    You can use this function I just wrote:

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

    It works just like the normal $.hover except there is a 400ms delay before the mouse leave event is called (which is cancelled if you move your mouse back in within that timeframe).

    0 讨论(0)
  • 2021-01-13 05:14
    (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 讨论(0)
提交回复
热议问题