background使用jquery更改图像
我正在从这段代码中更改我的背景图片
jQuery(window).load(function(){ var images = ['blaa.jpg','sdsd.jpg']; var i = 0; setInterval(function(){ jQuery('#absolute-c').css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); }, 3000); })
如何.animate
和加载第一个背景毫不拖延。 由于setInterval
我的第一个背景也在3秒后显示
您可以为此创建一个函数并在setInterval中使用它:
jQuery(window).load(function(){ var images = ['blaa.jpg','sdsd.jpg']; var i = 0; function changeBackground() { jQuery('#absolute-c').css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); } // Call it on the first time changeBackground(); // Set an interval to continue setInterval(changeBackground, 3000); });
另一个解决方案,我认为更好,是使用setTimeout
代替:
jQuery(window).load(function(){ var images = ['blaa.jpg','sdsd.jpg']; var i = 0; var timeoutVar; function changeBackground() { clearTimeout(timeoutVar); // just to be sure it will run only once at a time jQuery('#absolute-c').css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); // call the setTimeout every time to repeat the function timeoutVar = setTimeout(changeBackground, 3000); } // Call it on the first time and it will repeat changeBackground(); });