2011-06-05 126 views
1
$('#cart > .heading a').bind('mouseenter', function() { 
    $('#cart').addClass('active'); 


    $.ajax({ 
     url: 'index.php?route=checkout/cart/update', 
     dataType: 'json', 
     success: function(json) { 
      if (json['output']) { 
       $('#cart .content').html(json['output']); 
      } 
     } 
    });   

    $('#cart').bind('mouseleave', function() { 
     $(this).removeClass('active'); 
    }); 
}); 

我需要延遲mouseleave上的removeClass。我可以簡單地添加一個this.delay行嗎?Jquery延遲事件

+0

有點建議:而不是mouseenter,mouseleave use .hover(...,...) – 2011-06-05 00:26:19

回答

5

你可以只使用setTimeout()

$('#cart').bind('mouseleave', function() { 
    var $that = $(this); 
    setTimeout(function(){$that.removeClass('active');}, 500); //500 millisec delay 
}); 
+0

完美工作。 – 2011-06-05 00:31:25

3
$('#cart > .heading a').hover(function() { 
    // clear the previously defined timeout if any 
    clearTimeout($(this).data('timeout')); 
    $(this).addClass('active'); 
    // do other stuff here 
}, function() { 
    // set timeout and save it in element's state 
    // so it could be removed later on if needed 
    var e = $(this).data('timeout', setTimeout(function() { 
     e.removeClass('active'); 
    }, 3 * 1000)); // 3 sec. 
}); 

這樣.removeClass(「激活」)。只有當鼠標位於元素之外採取行動。

+0

'this'不會是超時內的元素。 – 2011-06-05 00:49:11