在无限循环中使用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,但我对如何遍历数组有点迷失?
答案 0 :(得分:2)
计数器变量和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);
答案 1 :(得分:0)
有一个名为setInterval
的东西。
var count = 0;
var div = document.getElementById('a');
var btn = document.getElementById('b');
var interval = setInterval(function(){
div.innerText = count;
count++;
}, 1000);
btn.addEventListener('click', function(){
clearInterval(interval);
});
<div id="a">0</div>
<button id="b">Stop</button>