2016-04-22 6 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'); 
     } 
    }) 
}; 
関連する問題