$(this).animate({top:200},500); TOP变成一个变量?

时间:2010-11-29 13:46:36

标签: jquery jquery-animate

我很难解释所以我只会展示我想要做的事情:

这项工作很好:

$(this).animate({ top: 200 }, 500);

我正在尝试用变量

替换'top'值 像这样:

var x = 'top';    
if (condition) { x = 'left'; }    
$(this).animate({ x: 200 }, 500);

但这失败了。

4 个答案:

答案 0 :(得分:3)

您正在传递一个对象 - 事先像这样定义它。其中x可以是任何东西,即'top','left'等等。

obj[x] = 200;

$(this).animate(obj, 500);

答案 1 :(得分:2)

你可以试试这个。

var pos = {'top':200};    
if (condition) { pos = {'left':200}; }    
$(this).animate(pos, 500);

答案 2 :(得分:0)

顶部是parameter。您可以传递任何CSS属性。

  

动画将移动的CSS属性的地图。

答案 3 :(得分:0)

我参加派对有点晚了,但如果您使用ES6,可以用它来计算对象密钥:

x = 'top';    
if (condition) { x = 'left'; }    
$(this).animate({ [x]: 200 }, 500);

参考:MDN

相关问题