How to tell .hover() to wait?

2019-01-07 03:59发布

I have a drop down menu. Now when it's slided down to multiple levels, I'd like it to add wait time for like 2 secs, before it disappears, so the user can get back in, when he breaks the .hover() by mistake.

Is it possible?

my code for the slide:

$('.icon').hover(function() {
        $('li.icon > ul').slideDown('fast');
    }, function() { 
        $('li.icon > ul').slideUp('fast');
    });

9条回答
聊天终结者
2楼-- · 2019-01-07 04:47

I would like to add to Paolo Bergantino that you can do this without the data attribut:

var timer;
$('.icon').hover(function() {
    clearTimeout(timer);
    $('li.icon > ul').slideDown('fast');
}, function() {
    timer = setTimeout(function() {
        $('li.icon > ul').slideUp('fast');
    }, 2000);
});
查看更多
狗以群分
3楼-- · 2019-01-07 04:52
$('.icon').on("mouseenter mouseleave","li.icon > ul",function(e){
   var $this = $(this);
   if (e.type === 'mouseenter') {
       clearTimeout( $this.data('timeout') );
       $this.slideDown('fast');
   }else{ // is mouseleave:
       $this.data( 'timeout', setTimeout(function(){
           $this.slideUp('fast');
       },2000) );  
   }
 });
查看更多
乱世女痞
4楼-- · 2019-01-07 04:56

I think this is code your need:

    jQuery( document ).ready( function($) {  
    var navTimers = [];  
    $('.icon').hover(function() { 
            var id = jQuery.data( this );  
            var $this = $( this );  
            navTimers[id] = setTimeout( function() {  
                $this.children( 'ul' ).slideDown('fast');  
                navTimers[id] = "";  
            }, 300 );  
        },  
        function () {  
            var id = jQuery.data( this );  
            if ( navTimers[id] != "" ) {  
                clearTimeout( navTimers[id] );  
            } else {  
                $( this ).children( "ul" ).slideUp('fast'); 
            }  
        }  
    );  
}); 
查看更多
登录 后发表回答