我正在使用一些jQuery来在网站上创建CSS淡入淡出效果。它工作得很好。但由于阵列中只有4个图像,因此很可能连续两次加载相同的图像。
我可以添加什么来防止这种情况?
我目前的jQuery代码如下:
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
提前致谢。
干杯
答案 0 :(得分:1)
您可以一个接一个地显示您的图像(并在整个时间重复这一过程):
var counter = 0;
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[counter] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
counter++;
nextBG = "url(" + imgArray[counter % imgArray.length] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
或随机选择:
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var current = Math.floor(Math.random() * imgArray.length);
var nextBG = "url(" + imgArray[current] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
var copy = imgArray.slice(0); // make copy
copy.splice(current, 1); // remove current
current = Math.floor(Math.random() * copy.length);
nextBG = "url(" + copy[current] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval