使用动态变量作为对象文字,jQuery动画功能

时间:2012-11-05 16:41:48

标签: javascript jquery jquery-ui

最初我有

targetWater.animate({
    "width": "+=100%"

现在我想动态使用“width”或“height”

var direction = (targetWater.hasClass('x'))? "width" : "height";
targetWater.animate({
    direction: "+=100%"

但这不起作用。

我试过

direction.toString()

''+direction+''

不喜欢这个

var anim = { direction: "+=100%" }
targetWater.animate(anim,

6 个答案:

答案 0 :(得分:8)

您的方法不起作用,因为direction被解释为键,而不是变量。

你可以这样做:

var animation = {};
var direction = targetWater.hasClass('x') ? "width" : "height"
animation[direction] = "+=100%";
targetWater.animate(animation);

方括号使得可以动态地拥有密钥。


如果您希望键"direction"使用方括号表示法,您可以写:

animation["direction"];

相当于:

animation.direction;

答案 1 :(得分:2)

使用括号表示法:

var anim = {};
anim[direction] = "+=100%";

答案 2 :(得分:2)

您的变量未进行插值,您需要按以下方式定义:

var options = {};
options[direction] = "+=100%";

targetWater.animate( options , /*...*/

答案 3 :(得分:2)

我建议您将其创建为属性并将其传递给.animate函数。见下文,

var direction = (targetWater.hasClass('x'))? "width" : "height";

var animProp = {};
animProp[direction] = "+=100%";

targetWater.animate(animProp, /*..*/);

答案 4 :(得分:2)

您可以使用“类似数组”(括号)表示法来创建“正确”/动态属性:

var animation = {};
animation[targetWater.hasClass('x'))? "width" : "height"] = "+=100%";

targetWater.animate(animation);

答案 5 :(得分:2)

不,你不能在键内使用变量。您使用括号表示法构建对象

var anim = {};
anim[ targetWater.hasClass('x') ? "width" : "height" ] = "+=100%";
targetWater.animate(anim, …

或您不使用对象

targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", …
相关问题