$(this).animate({ top: 200 }, 500); TOP to be a variable?
It is hard for me to explain so I will just demonstrate what I am trying to do:
This work fin开发者_如何学编程e:
$(this).animate({ top: 200 }, 500);
I'm trying to replace the 'top' value by a variable
like this:
var x = 'top';
if (condition) { x = 'left'; }
$(this).animate({ x: 200 }, 500);
But this fail.
You are passing an object - define it beforehand like this. Where x can be anything, i.e. 'top', 'left', etc.
obj[x] = 200;
$(this).animate(obj, 500);
You can try this.
var pos = {'top':200};
if (condition) { pos = {'left':200}; }
$(this).animate(pos, 500);
Top is a parameter. You can pass any CSS properties.
A map of CSS properties that the animation will move toward.
I'm a bit late to the party, but you could use this to compute object keys if you use ES6:
x = 'top';
if (condition) { x = 'left'; }
$(this).animate({ [x]: 200 }, 500);
Reference: MDN
精彩评论