2013-01-16 85 views
1

我有一個菜單。在這個菜單中我有一些隱藏的子菜單,所以我在懸停操作後顯示它。我也對子菜單顯示有一些延遲效果。現在我想添加相同的效果來隱藏它。但它不起作用。另外我怎麼能在懸停/ mouseenter下一個菜單元素上添加一些延遲?如何使用jQuery延遲mouseleave動作

$('.main_menu ul li').on({ 
    mouseenter: function(){ 
     var self = this, 
      time = 200; 
     $(self).data('timer', setTimeout(function(){ 
      $(self).children('.sub_menu_main').addClass('opened'); 
     }, time)); 
    }, 
    mouseleave: function(){ 
     var self = this, 
      time = 200; 
     clearTimeout($(self).data('timer')); 
     setTimeout(function() { 
      $(self).children('.sub_menu_main').removeClass('opened'); 
     }, time); 
    } 
}); 
+0

* HTTP://stackoverflow.com/questions/3709255/add-delay-to-mouseleave-in-jquery* –

回答

3

我取得了良好的解決了這個問題,所以:

var timer; 
$('.main_menu ul li').on({ 
    mouseenter: function(){ 
     var self = this; 
     clearTimeout(timer); 
     timer = setTimeout(function(){ 
      $(self).children('.sub_menu_main').addClass('opened'); 
     }, 100) 
    }, 
    mouseleave: function(){ 
     var self = this; 
     setTimeout(function(){ 
      if (!$(self).children('.sub_menu_main').is(":hover")){ 
       $(self).children('.sub_menu_main').removeClass('opened'); 
      } 
     }, 100); 
    } 
}); 
0

難道你不在你的mouseleave事件中使用self?該功能中的this是什麼?把debugger陳述,看看this是你認爲它指的東西。