为什么下面的工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
然而这是行不通的:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。
为什么下面的工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
然而这是行不通的:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。
当前回答
您可以为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
)
其他回答
ES6 / 2020
如果你试图使用“key:value”从任何其他来源将数据推入对象,你可以使用这样的方法:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
希望这能帮助到一些人:)
你可以这样做:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
您可以为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
)
我已经使用下面的方法来添加一个具有“动态”名称的属性到对象:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
Key是新属性的名称。
传递给animate的属性对象将是{left: 20, width: 100, top: 10}
这只是使用了其他答案所推荐的必需的[]符号,但是代码行数更少!
如果你想要对象键与变量名相同,在es2015有一个简短的手。 ECMAScript 2015中的新符号
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10