2014-09-05 50 views
0

我有這個簡單的代碼設置,當我mouseenter圖像,圖像淡出,一些文本信息淡入。我的問題是當我將鼠標懸停在圖像上時,它會記錄每個mouseenter並且連續淡入和淡出鼠標懸停在圖像上的次數。有什麼方法可以阻止這種行爲?反覆懸停在圖像上導致「mouseenter」記錄每一個懸停和淡入和淡出

$('article').mouseenter(function(e) { 
    $(this).children('img').fadeTo(500, 0.4); 
    $(this).children('.post-info').fadeIn(500); 
}).mouseleave(function(e) { 
    $(this).children('img').fadeTo(500, 1); 
    $(this).children('.post-info').fadeOut(500); 
}); 

回答

1

.stop()是解決

簡單來說,你只需要添加.stop()在每一條戰線的動畫漸變。

jsfiddle demo

$('article').mouseenter(function(e) { 
    $(this).children('img').stop().fadeTo(500, 0.4); 
    $(this).children('.post-info').stop().fadeIn(500); 
}).mouseleave(function(e) { 
    $(this).children('img').stop().fadeTo(500, 1); 
    $(this).children('.post-info').stop().fadeOut(500); 
}); 

作爲獎勵。這是我怎麼會已經寫了代碼:

jsfiddle demo

$('article').on("mouseenter mouseleave", function(e) { 

     // mouseenter variable returns true if mouseenter event is occurring 
     // and it returns false if event is anything but mouseenter. 
    var mouseenter = e.type === "mouseenter", 
     $this = $(this), 
     img = $this.children('img'), 
     postInfo = $this.children('.post-info'); 

     // Both of these use ternary if statements that are equal to: 
     // if (mouseenter) { var imgFade = 0.4; } else { var imgFade = 1; } 
     // if (mouseenter) { var postInfoFade = 'fadeIn'; } else { var postInfoFade = 'fadeOut'; } 
    var imgFade = mouseenter ? 0.4 : 1, 
     postInfoFade = mouseenter ? 'fadeIn' : 'fadeOut'; 

    img.stop().fadeTo(500, imgFade); 
    postInfo.stop()[ postInfoFade ](500); 

}); 
+0

謝謝!另外,我將使用您的代碼版本。 – J82 2014-09-05 12:52:10