2015-08-21 82 views
1

我使用.mouseenter()和.mouseleave()做一個動畫到我的按鈕。問題是,當我多次移動我的光標在按鈕,它不斷重複.mouseenter()我希望它完成動畫,一旦光標保持懸停在其上面,直到動畫時間完成,並且如果它在動畫完成之前離開按鈕,動畫應該停止。對於.mouseleave()如果在動畫完成之前將光標懸停在其上,則應停止動畫。 問題與.mouseleave()和.mouseenter()

 
 
    $(document).ready(function(){ 
 
    $('#button').mouseenter(function(){ 
 
     $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
 
    }); 
 
    $('#button').mouseleave(function(){ 
 
     $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
 
    }); 
 
    });
#button{ 
 
    width:100px; 
 
    height:50px; 
 
    background-color:red; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
 
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script> 
 
<div id="button"></div>

+0

你提到它不斷重複動畫。你想要它做什麼? – jasonwarford

+0

是否有一個原因,你這樣做與jQuery的?你可以用CSS實現同樣的效果。 – cocoa

+2

這就是這些事件應該如何工作。如果您想停止動畫,請參閱http://stackoverflow.com/questions/18211280/how-to-stop-an-animation-queue-in-jquery – Teemu

回答

2

您可以使用標誌進入和離開。然後檢查相應的標誌,並完成當前動畫當進入/離開事件發生,這樣的事情:

$(document).ready(function() { 
    var isEntering = false, // Create flags 
     isLeaving = false; 
    $('#button').mouseenter(function() { 
     isEntering = true; // Set enter flag 
     if (isLeaving) { // Check, if leaving is on process 
      $(this).finish(); // If leaving, finish it 
      isLeaving = false; // Reset leaving flag 
     } 
     $(this).animate({ 
      backgroundColor: '#ffce00', 
      width: '+=1em' 
     }, 100); 
    }); 
    $('#button').mouseleave(function() { 
     isLeaving = true; // Set leave flag 
     if (isEntering) { // Check if entering is on process 
      $(this).finish(); // If it is, finish it 
      isEntering = false; // Reset enter flag 
     } 
     $(this).animate({ 
      backgroundColor: '#1e7989', 
      width: '-=1em' 
     }, 100); 
    }); 
}); 

A live demo at jsFiddle

0

如果你只希望它運行一次,你可以在事件觸發後解除綁定:

$(document).ready(function(){ 
    $('#button').mouseenter(function(){ 
     $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
     $(this).unbind('mouseenter'); 
    }); 
    $('#button').mouseleave(function(){ 
     $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
     $(this).unbind('mouseleave'); 
    }); 
    }); 
+1

這不是'.one()'的用途嗎? – Barmar

+0

但我不認爲你理解這個問題。他不希望它只發生一次,他只是不希望它們重疊。 – Barmar

1

嘗試增加.stop(),它將從排隊停止動畫。

$(document).ready(function(){ 
    $('#button').mouseenter(function(){ 
     $(this).stop().animate({backgroundColor:'#ffce00',width:'+=1em'},100); 
    }); 
    $('#button').mouseleave(function(){ 
     $(this).stop().animate({backgroundColor:'#1e7989',width:'-=1em'},100); 
    }); 
}); 

問候, Gados

+0

當我在div上多次移動光標時,它會縮小直到它消失。 –