为什么下面的工作?

<something>.stop().animate(
    { 'top' : 10 }, 10
);

然而这是行不通的:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。


当前回答

给定的代码:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

翻译:

var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);

正如你所看到的,{thetop: 10}声明没有使用变量thetop。相反,它创建了一个具有名为thetop键的对象。如果你想让键值是顶部变量的值,那么你必须在顶部使用方括号:

var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);

方括号语法已在ES6中引入。在JavaScript的早期版本中,您必须执行以下操作:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);

其他回答

2020年更新/ example.com ...

一个更复杂的例子,使用括号和字面量…您可能需要做一些事情,例如使用vue/axios。把文字用括号括起来,所以

['…]']

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

你可以这样做:

var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);

给定的代码:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

翻译:

var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);

正如你所看到的,{thetop: 10}声明没有使用变量thetop。相反,它创建了一个具有名为thetop键的对象。如果你想让键值是顶部变量的值,那么你必须在顶部使用方括号:

var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);

方括号语法已在ES6中引入。在JavaScript的早期版本中,您必须执行以下操作:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);

使用ECMAScript 2015,你现在可以直接在对象声明中使用括号表示:

var obj = {
  [key]: value
}

其中key可以是返回值的任何类型的表达式(例如变量)。

你的代码看起来是这样的:

<something>.stop().animate({
  [thetop]: 10
}, 10)

在被用作键之前,top将被计算。

您可以为ES5执行以下操作:

var theTop = 'top'
<something>.stop().animate(
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)

或提取为一个函数:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)