制作无限动画jQuery

Ski*_*izo 6 javascript jquery

我想为div做一个无限的动画.
我成功地创造了一个无限移动的div,但它并不像一个一致的动画.div正在移动,然后再次调用该函数并再次移动,当动画停止并再次启动时,您会看到可以.
这是我做的代码:

this.movePipesHolder = function(){
    this.pos=this.pos-10;
    parent=this;
    $('#pipesHolder').animate({"left":this.pos},function(){
        parent.movePipesHolder();
    });
}
Run Code Online (Sandbox Code Playgroud)

我希望我能正确解释自己.

raz*_*zak 3

根据 JQuery 文档animate()采用以下参数:

.animate( properties [, duration ] [, easing ] [, complete ] )
Run Code Online (Sandbox Code Playgroud)

默认缓动设置为swing解释您正在经历的动画行为,要使动画以恒定的速度或速度移动,您需要将缓动设置为linear,要设置缓动参数,您还需要设置持续时间参数(默认持续时间)值为 400):

this.movePipesHolder = function()
{
    this.pos -= 10;
    parent = this;
    $('#pipesHolder').animate ({left: this.pos}, 400, 'linear', function()
    {
        parent.movePipesHolder();
    });
}
Run Code Online (Sandbox Code Playgroud)

这是JSFiddle上的一个工作示例。


编辑:

如果没有设置持续时间,缓动不起作用的原因:

在 JQuery 文档中,没有提到必须设置持续时间才能使缓动工作,因此我检查了 jquery 源代码以找出发生了什么。这是animateJQuery 插件v.2.1.4脚本中的函数:

animate: function (prop, speed, easing, callback)
{
    var empty = jQuery.isEmptyObject (prop),
        optall = jQuery.speed (speed, easing, callback),
        doAnimation = function()
        {
            // Operate on a copy of prop so per-property easing won't be lost
            var anim = Animation (this, jQuery.extend ({}, prop), optall);
            // Empty animations, or finishing resolves immediately
            if (empty || data_priv.get (this, "finish")) anim.stop (true);
        };
        ....
};
Run Code Online (Sandbox Code Playgroud)

它通过将,和参数传递给方法来创建optall对象,以下是脚本中声明的函数:speedeasingcallbackJQuery.speedJQuery.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;
    ......
}
Run Code Online (Sandbox Code Playgroud)

它表明:

  1. 提供的最后一个参数始终设置为回调函数(除非仅提供两个参数并且第二个参数不是函数或仅提供一个参数,在这种情况下回调将设置为 false)。
  2. 第二个参数始终设置为速度(稍后将对其进行验证,如果无效则更改为默认值)。
  3. 仅当提供四个参数时,缓动才会设置为第三个参数,或者如果第三个参数不是函数,则提供三个参数。

animate因此,当仅向第二个参数提供三个参数时,它被解释为speed而不是easing(除非第三个参数不是函数,否则它将用于easing)。

options然而,在阅读源代码后,我意识到(文档中也提到了)您可以传递对象中的最后三个参数,.animate (properties, options)并且在选项中您可以添加durationeasingcomplete或两个或全部的组合,例如:

$('#pipesHolder').animate ({left: this.pos}, {'easing': 'linear', 'complete': function()
{
    parent.movePipesHolder();
}});
Run Code Online (Sandbox Code Playgroud)