在.hide()w / jQuery之前添加延迟

我有一个简单的代码,当鼠标hover在它上面时保持元素可见,并在鼠标移出后隐藏它:

$(".item").hover( function () { $(this).show(); }, function () { $(this).hide(); } ); 

我想在它隐藏之前添加一些延迟,但添加$(this).delay(500).hide(); 似乎不起作用……

 var my_timer; $(".item").hover( function () { clearTimeout(my_timer); $(this).show(); }, function () { var $this = $(this); my_timer = setTimeout(function () { $this.hide(); }, 500); } ); 

这是一个演示: http : //jsfiddle.net/e3cNK/1/

如果您希望能够在隐藏元素后重新显示该元素,那么您需要更改元素的不透明度,而不是将其display更改为none 。 这将使元素保持在页面的常规流中,因此当用户将鼠标hover在隐藏元素上时,它可以再次显示:

 var my_timer; $(".item").hover( function () { var $this = $(this); $this.text('Mouse-Over'); clearTimeout(my_timer); $this.stop().fadeTo(250, 1); }, function () { var $this = $(this); $this.text('Mouse-Out'); my_timer = setTimeout(function () { $this.fadeTo(250, 0); }, 500); } ); 

这是一个演示: http : //jsfiddle.net/e3cNK/2/

没有任何参数的.delay()不使用效果队列(并且不必等待.delay() )。 相反,你可以使用$(this).delay(500).hide(0);