我有一个函数animate(),它会使用循环多次更改div背景。我创建了另一个函数animateReverse(),以便以相反的顺序播放图像序列,从最后一个图像结束开始。 animate()运行良好,但animateReverse()不起作用。我究竟做错了什么?
function changeImage(index) {
return function() {
var currentImage = './img/1/'+(index+1)+'.jpg';
$('#screen').css('background-image','url('+currentImage+')');
}
}
function animate(){
var numberOfPictures = 17;
for (var i = 0; i < numberOfPictures; i++) {
setTimeout(changeImage(i), i * waitPeriod);
}
};
var waitPeriod = 150;
function animateReverse(){
var numberOfPictures = 17;
for (var i = numberOfPictures - 1; i >= 0; i--) {
setTimeout(changeImage(i), i * waitPeriod);
}
};
答案 0 :(得分:1)
你animateReverse()
内的循环按此顺序调用setTimeout()
17次:
setTimeout(changeImage(16), 16 * 150);
setTimeout(changeImage(15), 15 * 150);
setTimeout(changeImage(14), 14 * 150);
setTimeout(changeImage(13), 13 * 150);
setTimeout(changeImage(12), 12 * 150);
setTimeout(changeImage(11), 11 * 150);
setTimeout(changeImage(10), 10 * 150);
setTimeout(changeImage(9), 9 * 150);
setTimeout(changeImage(8), 8 * 150);
setTimeout(changeImage(7), 7 * 150);
setTimeout(changeImage(6), 6 * 150);
setTimeout(changeImage(5), 5 * 150);
setTimeout(changeImage(4), 4 * 150);
setTimeout(changeImage(3), 3 * 150);
setTimeout(changeImage(2), 2 * 150);
setTimeout(changeImage(1), 1 * 150);
setTimeout(changeImage(0), 0 * 150);
当然,图像#0的计时器将首先触发,然后是图像#1的计时器,依此类推。
在animateReverse()
内你需要反转图像索引或超时值,但不能同时反转。
答案 1 :(得分:0)
较少的硬编码和最终的答案:
function changeImage(index,place) {
return function() {
var currentImage = './img/'+place+'/'+(index+1)+'.jpg';
$('.slider').css('background-image','url('+currentImage+')');
}
}
function anime(linear,x) {
changeImage();
// number of pictures
var numberOfPictures = 5;
// time
var waitPeriod = 700;
if(linear == true){
for (var i = 0; i < numberOfPictures; i++) {
setTimeout(changeImage(i,x), i * waitPeriod);
}
} else {
for (var i = numberOfPictures-1; i >= 0; i--) {
setTimeout(changeImage(i,x), (numberOfPictures - i) * waitPeriod);
}
}
};