开发者

Using variables in object property names

开发者 https://www.devze.com 2023-04-10 05:38 出处:网络
I have a variable called direction that stores either: left, right. I need to change the affected margin based on that variable.

I have a variable called direction that stores either: left, right.

I need to change the affected margin based on that variable.

Right now I'm using conditions, is it possible to r开发者_StackOverflow中文版eplace "left" with the output of the variable direction?

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


Not directly, but you can create an object and manipulate it before using it in animate():

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


Use this. Since there's no margin-up or margin-down, you have to "manually" translate it:

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

The second line is a legitimate, shorter way to write:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消