Javascript 使用动态变量作为对象文字,jQuery动画函数
原来我有Javascript 使用动态变量作为对象文字,jQuery动画函数,javascript,jquery,jquery-ui,Javascript,Jquery,Jquery Ui,原来我有 targetWater.animate({ "width": "+=100%" 现在我想动态使用“宽度”或“高度” 但这不起作用 我试过了 direction.toString() 及 这也没什么乐趣 var anim = { direction: "+=100%" } targetWater.animate(anim, 您的方法不起作用,因为方向被解释为一个键,而不是一个变量 你可以这样做: var animation = {}; var direction = tar
targetWater.animate({
"width": "+=100%"
现在我想动态使用“宽度”或“高度”
但这不起作用
我试过了
direction.toString()
及
这也没什么乐趣
var anim = { direction: "+=100%" }
targetWater.animate(anim,
您的方法不起作用,因为
方向
被解释为一个键,而不是一个变量
你可以这样做:
var animation = {};
var direction = targetWater.hasClass('x') ? "width" : "height"
animation[direction] = "+=100%";
targetWater.animate(animation);
方括号使您可以动态使用密钥
如果您希望键
“方向”
带有方括号符号,您可以写:
animation["direction"];
这相当于:
animation.direction;
使用括号表示法:
var anim = {};
anim[direction] = "+=100%";
如果变量没有插值,则需要按以下方式定义它:
var options = {};
options[direction] = "+=100%";
targetWater.animate( options , /*...*/
我建议您将其创建为属性,并将其传递给
.animate
函数。见下文
var direction = (targetWater.hasClass('x'))? "width" : "height";
var animProp = {};
animProp[direction] = "+=100%";
targetWater.animate(animProp, /*..*/);
可以使用“类数组”(括号)表示法创建“右”/“动态”属性:
var animation = {};
animation[targetWater.hasClass('x'))? "width" : "height"] = "+=100%";
targetWater.animate(animation);
不,不能在键内使用变量。要么使用括号表示法构建对象
var anim = {};
anim[ targetWater.hasClass('x') ? "width" : "height" ] = "+=100%";
targetWater.animate(anim, …
或者不使用对象
targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", …
+1、所有答案都是正确的,这个答案的格式和解释都很好。
var anim = {};
anim[ targetWater.hasClass('x') ? "width" : "height" ] = "+=100%";
targetWater.animate(anim, …
targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", …