根据 JQuery 文档
animate() 接受以下参数:
.animate( properties [, duration ] [, easing ] [, complete ] )
默认的缓动效果设置为
swing
,这解释了您所体验到的动画行为。要使动画以恒定的速度移动,您需要将缓动设置为
linear
。要设置缓动参数,您还需要设置持续时间参数(默认持续时间值为400):
this.movePipesHolder = function()
{
this.pos -= 10;
parent = this;
$('#pipesHolder').animate ({left: this.pos}, 400, 'linear', function()
{
parent.movePipesHolder();
});
}
这是一个有关IT技术的工作示例,可在
JSFiddle上使用。
编辑:
缓动不起作用的原因是没有设置持续时间:
JQuery文档中没有提到必须设置持续时间才能使缓动起作用,所以我检查了JQuery源代码以找出问题所在。这是JQuery插件v.2.1.4脚本中的animate
函数:
animate: function (prop, speed, easing, callback)
{
var empty = jQuery.isEmptyObject (prop),
optall = jQuery.speed (speed, easing, callback),
doAnimation = function()
{
var anim = Animation (this, jQuery.extend ({}, prop), optall);
if (empty || data_priv.get (this, "finish")) anim.stop (true);
};
....
};
通过向JQuery.speed
方法传递speed
、easing
和callback
参数,创建optall
对象,下面是脚本中声明的JQuery.speed
函数:
jQuery.speed = function (speed, easing, fn)
{
var opt = speed && typeof speed === "object" ? jQuery.extend ({}, speed) :
{
complete: fn || !fn && easing || jQuery.isFunction (speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction (easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
......
}
这说明:
- 提供的最后一个参数始终设置为回调函数(除非提供了两个参数且第二个不是函数,或者只提供了一个参数,在这种情况下回调将被设置为false)。
- 第二个参数始终设置为速度(稍后将对其进行验证,并在无效时更改为默认值)。
- 仅当提供了四个参数时才会将缓动设置为第三个参数,或者 如果第三个参数不是函数,则仅提供了三个参数。
因此,当仅向 animate
提供三个参数时,第二个参数将被解释为 speed
而不是 easing
(除非第三个参数不是函数,那么它将用于 easing
)。
但是,在阅读源代码后,我意识到(文档中也提到了),您可以在 options
对象中传递最后三个参数 .animate(properties,options)
,并且在选项中可以添加 duration
、easing
或 complete
或两者或全部的组合,例如:
$('#pipesHolder').animate ({left: this.pos}, {'easing': 'linear', 'complete': function()
{
parent.movePipesHolder();
}});