2012-05-28 64 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