无限查询动画无法使用延迟

时间:2016-02-10 22:09:41

标签: jquery animation

function enemy () {
            this.obj;
            this.create = function () {
                var obj_string = '<img src="img/char.jpg" class="enemy" style="position:absolute; left:' + this.P1[0] + 'px; top: ' + this.P1[1] + 'px; height:' + 100 + 'px;width:auto;">';
                this.obj = $($.parseHTML(obj_string));
                $("#layer_enemies").append(this.obj);
                this.anim();
            };
            this.anim = function () {
                $(this.obj).delay(this.WaitAtP1).show(0);
                $(this.obj).animate({left: '570px'},1000,function(){
                    $(this.obj).delay(this.WaitAtP2).show(0);
                    $(this.obj).animate({left: '200px'},1000,function(){
                        this.anim();
                    });
                });
            };
            this.create();
        };

动画在第一次向右移动后停止:( 我无法弄清楚为什么..

1 个答案:

答案 0 :(得分:0)

问题是this,在jQuery函数中,this不再是对象/类的引用,而是jQuery对象。因此你必须这样做:

this.anim = function () {
    var that = this;
    $(this.obj).delay(this.WaitAtP1).show(0);
    $(this.obj).animate({left: '570px'},1000,function(){
        $(that.obj).delay(that.WaitAtP2).show(0);
        $(that.obj).animate({left: '200px'},1000,function(){
            that.anim();
        });
    });
};

Working demo here

或者您使用jQuery.proxy方法(自1.4以来可用)。

相关问题