2016-04-22 35 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'); 
     } 
    }) 
}; 
相关问题