我正在使用 Greensock 动画库,在构建顺序动画时(一件事结束,下一件事立即开始),您必须像这样输入:
childTL.to($box, 1, {x:50,y:0})
.to($box, 1, {x:50,y:50})
.to($box, 1, {x:-50,y:50})
.to($box, 1, {x:-50,y:0});
我遇到的问题是,我将所有内容存储在数据库中或作为变量,因此需要使用 for 循环增量构建内容。
我想要的是这样的:
var animation = {
"name": "movearound",
"sequence": [{
"duration": "1",
"vars": {
"x": "50",
"y": "0"
}
}, {
"duration": "1",
"vars": {
"x": "50",
"y": "0"
}
}, {
"duration": "1",
"vars": {
"x": "50",
"y": "0"
}
}, {
"duration": "1",
"vars": {
"x": "50",
"y": "0"
}
}]
}
target = $(".target123")
childTL = new TimelineLite{onUpdate: updateSlider});
for (S = 0; S < animatelayers.sequence.length; S++) {
duration = animatelayers.sequence[S]["duration"];
sequence = animatelayers.sequence[S]["vars"];
if (S == 0) {
childTL.to(target, duration, sequence)
} else {
.to(".target", duration, sequence);
}
}
我知道我可以通过将字符串连接在一起然后对其执行 eval() 来做到这一点,但是有没有办法做到这一点?
编辑我为什么要谈论 eval():
我想我遇到的麻烦是,当涉及到字符串与对象时,Greensock 是多么挑剔 - 例如,您可以在 .to( 中使用 $("#target")
),但如果先将其定义为变量 var target = $("#target");
然后 childTL.to(target, 1, {x :50,y:0})
会失败,但如果你这样做 var target = "#target"
它将起作用。所以在过去,我创建了它,就像 Greensock 想要的那样,作为一个字符串,然后使用 eval()。虽然我可以继续这样做,但我更喜欢寻找更好的方法来完成事情。
最佳答案
您的示例代码没有任何意义,因此我将演示如何将原始代码段转换为使用数据结构和循环:
childTL.to($box, 1, {x:50,y:0})
.to($box, 1, {x:50,y:50})
.to($box, 1, {x:-50,y:50})
.to($box, 1, {x:-50,y:0});
首先我们定义数据:
var coords = [
{x: 50, y: 0},
{x: 50, y:50},
{x:-50, y:50},
{x:-50, y: 0}
];
然后我们循环:
var obj = childTL;
for (var i = 0; i < coords.length; i++) {
obj = obj.to($box, 1, coords[i]);
}
这是原始链式 .to(...).to(...).to(...)
调用的严格转换。然而,实际上没有必要这样做。为了方便起见,.to
方法只是返回对象(根据 https://greensock.com/docs/#/HTML5/Animation/TimelineLite/to/ );您不必使用它。
你可以简单地说:
for (var i = 0; i < coords.length; i++) {
childTL.to($box, 1, coords[i]);
}
关于javascript - 循环数组时如何避免 eval()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057319/