$('#menu > li').hover(function(){
$(this).find('ul').slideDown();
});
$('#menu > li').mouseleave(function(){
$(this).find('ul').slideUp();
});
这段代码本来是正常工作的,但如果我快速地多次将鼠标悬停/离开菜单中的一个
<li>
项目,当我停下来后,我会看到它上下滑动了多次。请观看这个短视频捕捉。
如何防止这种情况发生?
$('#menu > li').hover(function(){
$(this).find('ul').slideDown();
});
$('#menu > li').mouseleave(function(){
$(this).find('ul').slideUp();
});
<li>
项目,当我停下来后,我会看到它上下滑动了多次。如何防止这种情况发生?
您可以使用stop
停止当前的动画。您还可以将两个事件处理程序组合起来,只需使用hover
(它可以接受2个参数,第一个是在mouseenter
上运行的函数,第二个是在mouseleave
上运行的函数):
$('#menu > li').hover(function() {
$(this).find('ul').stop(true, true).slideDown();
}, function() {
$(this).find('ul').stop(true, true).slideUp();
});
第一个参数是 clearQueue
,它可以防止动画队列无限制地排队,因此您可以重复悬停。第二个参数是 jumpToEnd
,在开始新动画之前,它会强制结束当前正在运行的任何动画。
这里有一个简单的例子。
这一切都归结于您拥有一个变量,它将存储您的滑动状态,并且如果已经发生了滑动,则会防止进一步的请求。
在滑动开始时设置标志并使用回调函数取消标志。
var closing = false;
$('#menu > li').mouseleave(function(){
closing = true;
$(this).find('ul').slideUp(null, function(){
closing = false;
});
});
// then in the hover method you would just check the value of closing to see if to allow or not opening.