2013-06-19 35 views
0

我已經得到了多數民衆贊成步進元素的網頁上的動畫一個遞歸函數:JQuery動畫隊列按相反順序執行?

_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/

+0

任何機會,你可以建立一個小提琴? – musicnothing

+1

您正在調用*'_this.go()'並將其結果傳遞給'animate()'而不是傳遞方法本身。 –

+0

他是對的 - 使用'_this.go'而不是'_this.go()' – musicnothing

回答

3

寫:

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

你實際上調用go()並通過其返回值(undefined在我們的例子),以animate()

你應該通過函數本身,而不是:

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

您的回調函數被調用。

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

優秀的答案,現貨 - 弗雷德裏克只是打你到它= / – CodeMoose