我使用以下功能制作具有淡入和淡出效果的图像幻灯片。
var project_photos = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var project_photo_index = 0;
function nextPhoto() {
$('#background').fadeOut();
$('#background').css('background-image',
"url('images/" + project_photos[project_photo_index] + "')");
$('#background').fadeIn();
timer = setTimeout(function() {
if (project_photo_index+1 > project_photos.length) {
project_photo_index = 0;
} else {
project_photo_index++;
}
nextPhoto();
}, 5000);
}
但是,我想稍微调整一下这个函数,以消除fadeOut()
和fadeIn()
之间的白色时刻。我想要实现的是:
假设淡入和淡出时间为400毫秒,每张图像的显示时间为5秒
如何调整代码以使其按照描述工作?
答案 0 :(得分:2)
的 LIVE DEMO 强> 的
如果您使用2个DIV元素,则可以淡化内部元素:
<div id="bg2"><div id="bg1"></div></div>
这就是你所需要的:
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'],
n = images.length,
c = 0,
$1 = $('#bg1'),
$2 = $('#bg2');
$.fn.setBG = function(){
return this.css({backgroundImage: "url(images/"+ images[c] +")"});
};
(function loop(){
$1.setBG().fadeTo(0,1).delay(2000).fadeTo(1000, 0, loop);
c = ++c%n;
$2.setBG();
})();
这是如何运作的:
#bg1: set1 -- fadeOut -- set2 -- fadeOut -- set3 -- fadeOut -- set1 - ...
#bg2: - set2 ------------- set3 ------------- set1 ------------- set2 ...
答案 1 :(得分:1)
尝试类似
的内容var project_photos = ['//placehold.it/128/ff0000', '//placehold.it/128/ffff00', '//placehold.it/128/00ff00', '//placehold.it/128/00ffff'];
var project_photo_index = 0;
//preload the images
$.each(project_photos, function (i, src) {
var img = $('<img />', {
src: src
})
})
function nextPhoto() {
$('#background').fadeTo('normal', .5, function () {
$(this).css('background-image', "url('" + project_photos[project_photo_index] + "')")
$(this).fadeTo('normal', 1)
});
project_photo_index++;
project_photo_index = project_photo_index < project_photos.length ? project_photo_index : 0;
setTimeout(nextPhoto, 5000)
}
nextPhoto();
演示:Fiddle