问题描述
我想知道是否有人可以帮助我,或者为我指明正确的方向.我正在寻找一个jquery的片段,它将每隔5秒左右自动更改div的背景图像.我最初的bg图像是在CSS中设置的,但是我不确定如何创建函数以使其在图像阵列之间交换?
I was wondering if anyone could help me out, or point me in the right direction. I'm looking for a snippet of jquery that will automatically change the background image of a div every say 5 seconds or so. My initial bg image is set in css, but i'm not sure how to create the function to make it swap between an array of images?
我有5张图片:
bg-1.jpg,bg-2.jpg,bg-3.jpg,bg-4.jpg,bg-5.jpg.
bg-1.jpg, bg-2.jpg, bg-3.jpg, bg-4.jpg, bg-5.jpg.
当前,我的div设置为bg-1.jpg.
Currently my div is set to bg-1.jpg.
<div id="page_bg"></div>
实际上没有任何代码可显示,但是希望有人可以帮助我:)
Don't really have any code to show, but hopefully someone can help me out :)
推荐答案
这种方法应该可以解决问题
Something like this should do the trick?
jQuery( function( $ ) {
var images = [ "bg-1.jpg", "bg-2.jpg", "bg-3.jpg", "bg-4.jpg", "bg-5.jpg" ];
var currentImage = 0;
function changeBackground() {
$( '#page_bg' ).css( { backgroundImage: 'url(' + images[ ++currentImage ] + ')' } );
if ( currentImage >= images.length - 1 ) {
currentImage -= images.length;
}
}
setInterval( changeBackground, 5000 );
});
这篇关于jQuery的简单动画/旋转的div内的CSS背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!