0

我有一个递归函数,可以在页面上步进元素的动画:

_this = this;
this.x = 0, this.y = 0;
this.targX = 5, this.targY = 5; 

this.go = function(){
    var xDir = 0, yDir = 0, finished = false;

    if(this.x>this.targX){
        console.log("Reverse x");
        xDir = -1;
    }else if(this.x<this.targX){
        console.log("Forward x");
        xDir = 1;
    }else{
        xDir = 0;
        if(this.y>this.targY){
            console.log("Reverse y");
            yDir = -1;
        }else if(this.y<this.targY){
            console.log("Forward y");
            yDir = 1;
        }else{  finished = true;  }
    }
    this.x+= xDir;
    this.y+= yDir;

    if(finished==false){
        this.$c.animate({
            left: "+="+32*xDir,
            top: "+="+32*yDir
        }, 200, _this.go());
    }
}

希望从代码中可以清楚地看出这一点,但是动画应该首先在 x 方向上步进,直到this.x= this.targX,然后在 y 方向上步进,直到this.y= this.targY。在这种情况下,元素向右移动 5 步,然后向下移动 5 步。

然而,在实践中,动画下降 5 步然后向右 5 步 - 好像动画队列正在反转。如果我取消_this.go()对成功的调用,该元素会向右走一步并停止 - 所以我知道我的轴不会在某个地方混淆。控制台日志甚至以正确的顺序报告:

Forward x
Forward x
Forward x
Forward x
Forward x
Forward y
Forward y
Forward y
Forward y
Forward y

这是怎么回事,为什么动画队列是反向执行的?我做错了什么,还是 JQuery 的预期行为?


编辑:这里小提琴:http: //jsfiddle.net/WdYvB/

4

2 回答 2

3

By writing:

this.$c.animate({
    left: "+=" + 32 * xDir,
    top: "+=" + 32 * yDir
}, 200, _this.go());

You're actually calling go() and passing the value it returns (undefined in our case) to animate().

You should pass the function itself instead:

this.$c.animate({
    left: "+=" + 32 * xDir,
    top: "+=" + 32 * yDir
}, 200, _this.go);
于 2013-06-19T18:51:13.003 回答
0

Your callback function is being called when you are assigning the callback.

  if(finished==false){
        this.$c.animate({
            left: "+="+32*xDir,
            top: "+="+32*yDir
        }, 200, _this.go());  // should be _this.go 
    }
于 2013-06-19T18:50:16.197 回答