jQuery:点击时,防止鼠标进入事件

6
我有两个不同的动画效果,一个在mouseenter触发,另一个在click触发。问题是当它们同时激活时会产生抖动的动画效果。
您可以在此处查看示例:JSFiddle 如果激活了click事件,是否有可能防止mouseenter事件的发生? Javascript
$('header h1').mouseenter(function() {
  $('header:not(.open)').delay(500).animate({
    'padding-bottom': '40px'
  }, 150, function() {
    //function complete
  });
});

$('header h1').mouseleave(function() {
  $('header:not(.open)').animate({
    'padding-bottom': '20px'
  }, 150, function() {
    //function complete
  });
});

$('header h1').click(function() {

  if ($('header').hasClass('open')) {
    $('header p').fadeOut(100);
    $('header').removeClass('open').animate({
      'padding-bottom': '20px'
    }, 300, function() {
      //animation complete
    });
  }

  else {
    $('header').addClass('open').animate({
      'padding-bottom': '150px'
    }, 300, function() {
      $('header p').fadeIn();
    });
  }

});​

为什么你需要延迟半秒钟? - mayhewr
@mayhewr 我加了延迟以突出问题。但是问题仍然存在。 - colindunn
似乎unbind可以起作用?http://api.jquery.com/unbind/ - colindunn
您选择的答案是否解决了问题? - Dan
4个回答

4
似乎更容易只是这么做:
$('header').on({
    mouseenter: function(e) {
        if (!$(this).is('.open')) {
            $(this).stop(true, true).delay(500).animate({'padding-bottom': '40px' }, 150, function() {
                //function complete
            });
        }
    },
    mouseleave: function(e) {
        if (!$(this).is('.open')) {
            $(this).stop(true, true).animate({'padding-bottom': '20px'}, 150, function() {
            //function complete
            });
        }
    },
    click: function() {
        if ($(this).is('.open')) {
            $(this).find('p').fadeOut(100).end().removeClass('open').stop(true, true).animate({'padding-bottom': '20px'}, 300, function() {
                //animation complete
            });
        }else{
            $(this).addClass('open').stop(true, true).animate({'padding-bottom': '150px'}, 300, function() {
                $('p', this).fadeIn();
            });
        }
    }
});​

2
不行,尤其是因为这些事件是相互依赖的:要单击一个元素,您需要使用鼠标进入它:您无法停用已发生的 enter 事件。而且当进入时,显然不应该停用未来的 click 事件。

解决跳动动画问题的方法应该是 stop() 方法,它可以结束选定元素上正在运行的动画。


感谢您的解释。如果能帮忙实现stop()方法,将不胜感激。 - colindunn
在 .animate(...) 之前插入 .stop()。 - Bergi

0

延迟后检查open类怎么样?

从...改变

$('header h1').mouseenter(function() {
  $('header:not(.open)').delay(500).animate({
    'padding-bottom': '40px'
  }, 150, function() {
    //function complete
  });
});

$('header h1').mouseenter(function() {
  $.delay(500);
  $('header:not(.open)').animate({
    'padding-bottom': '40px'
  }, 150, function() {
    //function complete
  });
});

显然,您可以根据自己的喜好微调延迟时间,但是想法大致如下:

如果在x毫秒内没有点击,则增加填充。


0

看起来你需要 .stop()

将这段代码添加到你的 click 事件的开头:

$('header').stop(true)

对于 true 的第一个参数是 clearQueue,它将清除您的动画队列。

请参考此 jsFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接