2016-04-22 2 views
3

ErklärungWie ändert man die Dauer einer jQuery-Animation, bevor sie abgeschlossen ist?

Ich versuche Dauer einer jQuery Animation zu ändern, bevor es fertig ist, so schrieb ich den Code der Animation in einer Funktion, wobei die Dauer eine Variable ist. Die Animation hat queue: false, um sofort zu starten, wenn die Variable der Dauer geändert wird und die Funktion erneut mit einer Schaltfläche aufgerufen wird.

enter image description here

Das Problem:

Wenn ich auf der erwähnte Taste die Animation durantion ändert, aber wenn es es beginnt wieder mit der vorherige Dauer zu beenden. Hier ist eine fiddle mit dem Code.

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>

Antwort

1

Das Problem ist, dass nach der zweiten Animation läuft beendet hat, hat die erste Animation noch nicht abgeschlossen. Fügen Sie der vorherigen Animation einfach einen stop() hinzu.

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'); 
     } 
    }) 
}; 
Verwandte Themen