Using variables in object property names
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);
精彩评论