jQuery以随机间隔将背景图像更改为几个div

我的网站上有几个显示在一起的div,每个div都有不同的背景图像。 我创建了一个脚本,以随机的时间间隔更改背景图像,然而,脚本同时更改所有图像….我希望每个图像随机更改,完全独立于另一个….我也希望它们褪色,但时机是关键问题。

这是我正在使用的脚本。

jQuery(window).load(function(){ var images = ['images/gallery/gallery2thumb.jpg','images/gallery/gallery3thumb.jpg','images/gallery/gallery4thumb.jpg','images/gallery/gallery5thumb.jpg','images/gallery/gallery6thumb.jpg','images/gallery/gallery7thumb.jpg','images/gallery/gallery8thumb.jpg','images/gallery/gallery9thumb.jpg',]; var i = 0; var timeoutVar; function changeBackground() { clearTimeout(timeoutVar); // just to be sure it will run only once at a time jQuery('.hexagon-in2.change').css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); timeoutVar = setTimeout(changeBackground, ( 300+Math.floor(Math.random() * 1700) )); } changeBackground(); }); 

另见我的JSFiddle http://jsfiddle.net/QwJfn/2/

我怎样才能让每个div以随机的时间间隔改变背景图像但是独立?

检查一下:

  var images = ['http://www.placekitten.com/250/300','http://www.placekitten.com/260/300','http://www.placekitten.com/260/310']; var i = 0; var allDivs = []; function changeBackground() { allDivs = $(".hexagon-in2").each(function(){ setBG($(this),1000); }); } function setBG(div, time){ var timeVar; clearTimeout(timeVar); if( div == undefined){ return; } div.css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); timeVar = setTimeout(setTimer, time); } function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function setTimer(){ var imageIndex = getRandomInt(0,allDivs.length); setBG($(allDivs[imageIndex]),3000); } $(function(){ changeBackground(); }); 

在这里工作小提琴: http : //jsfiddle.net/QwJfn/10/

您需要为每个div注册一个单独的超时。

或者,您可以选择随机div来每次更改并减少超时因子,以便更频繁地运行该函数:

 function changeBackground() { clearTimeout(timeoutVar); // just to be sure it will run only once at a time var elements = jQuery('.hexagon-in2.change'); jQuery(elements[Math.floor(Math.random() * (elements.length + 1))]).css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); timeoutVar = setTimeout(changeBackground, ( 300+Math.floor(Math.random() * 1700) )); }