什么是拥有背景图像数组并在无限循环中使用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/