我的图片文件夹中有5张jpg图片。我想要一个div来自动逐个改变背景。如何使用jQuery做到这一点?
我可以使用jQuery操作一次background属性,但是当我尝试自动更改并循环时,我会陷入困境。
$( document ).ready(function() {
$(".topstrip").css('background-image', 'url("/static/img/website/banner/factory_plane-normal.jpg")')
});
答案 0 :(得分:7)
使用setInterval函数。示例代码。
$(document).ready(function () {
var imageFile = ["Image.jpg", "Image1.jpg", "Image2.jpg", "Image4.jpg"];
var currentIndex = 0;
setInterval(function () {
if (currentIndex == imageFile.length) {
currentIndex = 0;
}
$(".topstrip").css('background-image', 'url("/static/img/website/banner/' + imageFile[currentIndex++] + '")');
}, 3000);
});
答案 1 :(得分:0)
<div class="topstrip" style="height:100px;width:100px;"></div>
<script>
var imagebackground = 0;
var imgbackgrounds = [];
imgbackgrounds[0] ='/images/image1.jpg';
imgbackgrounds[1] ='/images/image2.jpg';
imgbackgrounds[2] ='/images/image3.jpg';
imgbackgrounds[3] ='/images/image4.jpg';
imgbackgrounds[4] ='/images/image5.jpg';
function changeimage() {
imagebackground++;
if(imagebackground > 4) imagebackground = 0;
$('.topstrip').fadeToggle("slow",function() {
$('.topstrip').css({
'background-image' : "url('" + imgbackgrounds[imagebackground] + "')"
});
$('.topstrip').fadeToggle("slow");
});
setTimeout(changeimage, 5000);
}
$(document).ready(function() {
setTimeout(changeimage, 5000);
});
</script>