拥有一组背景图像并在无限循环中使用 js/jquery 遍历它们的最佳方法是什么?
这是我目前所拥有的:
//ANIMATE JUMBOTRON BACKGROUND IMAGE
$(document).ready(function() {
var backgroundImage = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
];
$('.jumbotron').css('background-image', backgroundImage[0]);
})
这显然只是数组和简单的 css,但我对如何遍历数组有点迷茫?
最佳答案
计数器变量和 window.setInterval
应该可以。每次运行间隔函数时增加计数器 - 一旦达到背景图像数组的长度,将其重置为 0。
var backgroundImages = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
],
backgroundImageCounter = 0,
jumbotron = $('.jumbotron');
window.setInterval(function() {
jumbotron.css('background-image', backgroundImages[backgroundImageCounter]);
backgroundImageCounter++;
if(backgroundImageCounter >= backgroundImages.length) {
backgroundImageCounter = 0;
}
}, 5000);
关于javascript - 无限循环中的jquery动画背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283915/