jQuery:单击时,防止鼠标输入事件

jQuery: On click, prevent mouseenter event

本文关键字:鼠标 输入 入事件 单击 jQuery      更新时间:2023-09-26

我有两个单独的动画正在发生,一个在mouseenter click上触发。问题是,当它们都被激活时,它会创建一个跳跃的动画。

你可以在这里明白我的意思:JSFiddle

如果激活click事件,是否可以防止发生mouseenter事件?

爪哇语

$('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();
    });
  }
});​

这样做似乎更容易:

$('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();
            });
        }
    }
});​

不,你不能。特别是因为这些事件是相互基于的:要单击元素,您需要用鼠标输入它:您无法停用单击时已经发生的enter事件。而且您显然不应该在进入时停用未来的click事件。

跳转动画问题的解决方案应该是stop()方法,该方法结束对选定元素的运行动画。

延迟后检查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 毫秒之前未单击,请增加填充。

听起来你需要.stop().

将此添加到click事件的开头:

$('header').stop(true)

true 的第一个参数是 clearQueue ,这将清除动画队列。

看到这个 jsFiddle.