2012-05-28 68 views
6

我有两个独立的动画正在发生,其中一个在mouseenter上触发,另一个在click上触发。问题是,当它们都被激活时,它会创建一个跳动的动画。jQuery:单击时,阻止mouseenter事件

你可以明白我的意思是:JSFiddle

是否有可能阻止mouseenter事件从如果click事件被激活时发生的?

的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(); 
    }); 
    } 

});​ 
+0

为什么你需要半秒延时? – mayhewr

+0

@mayhewr我加了延迟来强调问题。但无论如何它仍然存在。 – colindunn

+0

看起来像取消绑定可能工作? http://api.jquery.com/unbind/ – colindunn

回答

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() method,它会在选定的元素上结束运行动画。

+0

感谢您的解释。执行'stop()'方法的任何帮助将不胜感激 – colindunn

+0

只需在.animate(...) – 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) 

第一个参数为真为clearQueue,它会清除你的动画队列。

看到这个jsFiddle

+0

之前插入.stop(),您是否忘记更新JSFiddle? – colindunn

+0

糟糕。 http://jsfiddle.net/NznC8/1/ – Calvin