2016-04-22 62 views
3

說明如何在jQuery動畫完成之前更改其持續時間?

我想它完成之前改變一個jQuery動畫的時間,所以我寫了一個函數,其中持續時間是可變的內部動畫的代碼。動畫有queue: false當持續時間的變量發生變化時立即啓動,並且用按鈕再次調用該功能。

enter image description here

問題

當我提到的按鈕,點擊該動畫durantion變化,但是當它完成它與之前的持續時間重新開始。 這是一個帶有代碼的fiddle

var dur; 
 

 
function foo(){ 
 
    $('.content').animate({width: '100%'}, 
 
    { 
 
    \t duration: dur, 
 
     easing: 'linear', 
 
    \t queue: false, 
 
     done: function(){ 
 
     \t $(this).css({width: '0%'}); 
 
     console.log('Prueba'); 
 
     } 
 
    }) 
 
}; 
 

 
$('.start').click(function(){ 
 
    dur = 5 * 1000; 
 
    foo(); 
 
}); 
 

 
$('.dur').click(function(){ 
 
    \t dur = 0.5 * 1000; 
 
    \t foo(); 
 
});
.content { 
 
    width: 0%; 
 
    height: 20px; 
 
    float: left; 
 
    margin-top: 20px; 
 
    background: #fdcfa2; 
 
    border: 1px solid #b18963; 
 
    color: #b18963; 
 
} 
 

 
button { 
 
    width: 50%; 
 
    cursor: pointer; 
 
    padding: 15px 0; 
 
    float: left; 
 
    background: #d0fac0; 
 
    border: 1px solid #6f9b5e; 
 
    color: #6f9b5e; 
 
} 
 

 
button:nth-child(2) { 
 
    background: #fff4a8; 
 
    border: 1px solid #b1a763; 
 
    color: #b1a763; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="start">Start</button> 
 
<button class="dur">Duration to 0.5 s</button> 
 

 
<div class="content"></div>

回答

1

的問題是,第二個動畫結束後運行,第一個動畫尚未完成。只需將stop()添加到以前的動畫中,就像這樣。

function foo(){ 
    $('.content').stop(); // stops the previous animation if running 
    $('.content').animate({width: '100%'}, 
    { 
     duration: dur, 
     easing: 'linear', 
     queue: false, 
     done: function(){ 
      $(this).css({width: '0%'}); 
      console.log('Prueba'); 
     } 
    }) 
};