2012-11-05 82 views
4

我原本,jQuery的動畫功能

targetWater.animate({ 
    "width": "+=100%" 

現在我要動態地使用「寬度」或「高度」

var direction = (targetWater.hasClass('x'))? "width" : "height"; 
targetWater.animate({ 
    direction: "+=100%" 

但這不起作用。

我已經試過

direction.toString() 

''+direction+'' 

沒有喜悅與此兩種

var anim = { direction: "+=100%" } 
targetWater.animate(anim, 

回答

8

因爲direction你的辦法行不通被解釋爲關鍵,不一個變量。

你能做到像這樣:

var animation = {}; 
var direction = targetWater.hasClass('x') ? "width" : "height" 
animation[direction] = "+=100%"; 
targetWater.animate(animation); 

的方括號做,所以你可以關鍵動態。


如果您想關鍵"direction"用方括號你可以這樣寫:

animation["direction"]; 

這相當於:

animation.direction; 
+0

+1,所有的答案都是正確的,這是一個很好的格式和解釋。 – jbabey

+0

非常感謝你 – Titan

2

使用括號標記:

var anim = {}; 
anim[direction] = "+=100%"; 
2

Yo ü變量不插,你需要將它定義方式如下:

var options = {}; 
options[direction] = "+=100%"; 

targetWater.animate(options , /*...*/ 
+0

這個作品謝謝你! – Titan

2

我建議你將其創建爲一個屬性,並將其傳遞給.animate功能。見下文,

var direction = (targetWater.hasClass('x'))? "width" : "height"; 

var animProp = {}; 
animProp[direction] = "+=100%"; 

targetWater.animate(animProp, /*..*/); 
2

你可以使用「陣列式」(括號)符號創建「正確」 /動態屬性:

var animation = {}; 
animation[targetWater.hasClass('x'))? "width" : "height"] = "+=100%"; 

targetWater.animate(animation); 
2

不,你不能使用內部的密鑰變量。要麼你打造的對象,具有支架符號

var anim = {}; 
anim[ targetWater.hasClass('x') ? "width" : "height" ] = "+=100%"; 
targetWater.animate(anim, … 

,或者您不使用對象

targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", …