我有一个看起来像这样的javascript对象,
var telephones = {
/*
"phone" : {
duration : time it takes to animate element in,
leftIn : position of element once on the incoming animation
leftOut : position of element on the outgoing animation
delay : delay between two animations
}
*/
"phone1": {
duration : 850,
leftIn : "408px",
leftOut : "9999px",
delay : 0,
},
"phone2" : {
duration : 600,
leftIn : "962px",
leftOut : "999px",
delay : setDelay(),
},
"phone3" : {
duration : 657,
leftIn : "753px",
leftOut : "9999px",
delay : 0,
},
"phone4" : {
duration : 900,
leftIn : "1000px",
leftOut : "9999px",
delay : setDelay(),
},
"phone5" : {
duration : 1200,
leftIn : "800px",
leftOut : "9999px",
delay : 0,
},
"phone6" : {
duration : 792,
leftIn : "900px",
leftOut : "9999px",
delay : setDelay(),
},
};
我正在使用上面的对象来尝试幻灯片中的单个元素的动画,这已经通过jquery循环插件进行了动画处理。我正在以下列方式使用代码,
$('#slideshow').cycle({
fx: 'scrollHorz',
before : triggerParralex,
after : removeParralex,
easing : 'easeOutCubic',
speed : 2000
});
所以上面的代码启动循环插件。然后我使用前后回调来运行另外两个函数,这些函数看起来像这样,
function bgChange(curr, next, opts) {
var background = $(".current").attr('data-background');
$.backstretch(background, {target: "#backstrectch", centeredY: true, speed: 800});
}
function triggerParralex(curr, next, opts) {
//move any phones that are in the viewport
for (var key in telephones) {
var obj = telephones[key];
for (var prop in obj) {
if($(".current ." + key).length) { //does .custom .phone1/2/3/4/5/6 exist if it does we can carry on
setTimeout(function() {
$(".current ." + key).animate({
"left" : obj["leftOut"],
"opacity" : 0
}, obj["duration"]);
}, obj["delay"]);
}
}
}
//change the background
bgChange();
//remove the current class from the DIV
$(this).parent().find('section.current').removeClass('current');
}
function removeParralex(curr, next, opts) {
//give the slide a current class so that we can identify it.
$(this).addClass('current');
//animate in any phones that belong to the current slide
for (var key in telephones) {
var obj = telephones[key];
for (var prop in obj) {
console.log(obj["leftIn"])
if($(".current ." + key).length) { //does .custom .phone1/2/3/4/5/6 exist if it does we can carry on
setTimeout(function() {
$(".current .phone1").animate({
"left" : obj["leftIn"],
"opacity" : 1
}, obj["duration"]);
}, obj["delay"]);
}
}
}
}
我的问题如下,
我正在尝试动画我的截面元素中的图像,截面元素已经通过循环插件滑动,这对我来说感觉就像是在后期停止我的图像动画?
第二个问题似乎是,虽然我的脚本很乐意发现$(".current .phone1")
似乎只是从对象中添加了phone6的属性,但我已经创建了fiddle。
正如你可以从小提琴中看到的那样#slideshow
的部分正在循环,但是其中的图像没有动画......为什么?
答案 0 :(得分:0)
正如Felix Kling在评论中所说,你有一个经典的“封闭内循环”问题。
这是(经典)解决方案:
for (var key in telephones) {
if($(".current ." + key).length) { //does .custom .phone1/2/3/4/5/6 exist if it does we can carry on
var obj = telephones[key];
(function(obj){
setTimeout(function() {
$(".current .phone1").animate({
"left" : obj["leftIn"],
"opacity" : 1
}, obj["duration"]);
}, obj["delay"]);
})(obj);
}
}
这个想法是将obj嵌入另一个闭包中,将它与循环隔离开来,从而阻止它的变化。