假设你有一个很长的动画,你正在改变width:
var myTargetWidth = 500;
$(el).animate( { "width" : myTargetWidth }, 5000 );
Run Code Online (Sandbox Code Playgroud)
动画是异步的,因此您的代码会继续...几秒钟后,您决定将目标更改width为300...此时动画仍在运行...
如何在运行的动画中将targetWidth更改为其他值?
一种选择是使用stepjQueryanimate函数 ( API ) 中提到的函数来检查动画运行时的条件。
示例 JSFiddle:http : //jsfiddle.net/GweLA/13/
JS
var myTargetWidth = 500;
$(document).ready(function(){
$('.sample').animate( { "width" : myTargetWidth },{
duration : 5000,
step: function(now, fx) {
if($(this).width() > 200){
myTargetWidth = 300;
$(this).stop().animate({ "width" : myTargetWidth },1000);
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
CSS
.sample{
width:20px;
height:100px;
background-color:#cccccc;
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="sample">
width is supposed to be animated till 500 but it stops at 300
</div>
Run Code Online (Sandbox Code Playgroud)
解决方案2:
经过一番研究,我发现我们可以修改传递给 step 函数的参数start和end属性fx来控制动画。这种平滑的动画,但不是一个非常整洁的方式做它虽然。
示例 JSFiddle:http : //jsfiddle.net/GweLA/57/
JS
var myTargetWidth = 500;
var isExecuted = false;
$(document).ready(function(){
$('.sample').animate( { "width" : myTargetWidth },{
duration : 5000,
queue : false,
step: function(now, fx) {
//So that fx.start and fx.end is set only once
if($(this).width() > 200 && $(this).width() < 203){
if(!isExecuted){
fx.start = now-65;
fx.end = 300;
}
isExecuted = true;
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3814 次 |
| 最近记录: |