防止不必要地触发事件

时间:2012-01-18 11:20:10

标签: javascript jquery events

$('#menu > li').hover(function(){
     $(this).find('ul').slideDown();
});

$('#menu > li').mouseleave(function(){

     $(this).find('ul').slideUp();
});

这样可以正常工作,但是如果我多次快速地悬停/离开菜单的<li>项目,一旦我停下来,我会看到它在我徘徊时上下滑动,

请观看此类视频捕捉

http://www.screenr.com/dkes

¿怎么可以防止?

2 个答案:

答案 0 :(得分:5)

您可以使用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,它强制任何当前正在运行的动画在开始新动画之前结束。

这是simple example

答案 1 :(得分:0)

这一切归结为你有一个存储滑动状态的变量,如果滑动已经发生,将阻止进一步的请求发生。

在滑动开始时设置标志,并使用回调取消设置标志。

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.

詹姆斯·阿拉迪斯(James Allardice)早些时候提出了第二个想法,如果有效,我会更喜欢它。