How do I make my background change images automatically every 15 seconds? JavaScript? jQuery?
I know this sounds simple and I searched up and down the web for a script but cant find anything. I just want my backgrounds to change every 15 seconds or so a开发者_如何学Pythonutomatically. (like a photo slide show but as a background.) My style sheet is controls the bg image in the body tag. Thanks for the help.
With setInterval
, you can call an arbitrary function in, well, intervals:
(function() {
var curImgId = 0;
var numberOfImages = 42; // Change this to the number of background images
window.setInterval(function() {
$('body').css('background-image','url(/background' + curImgId + '.jpg)');
curImgId = (curImgId + 1) % numberOfImages;
}, 15 * 1000);
})();
Simple enough to do with setInterval:
var currentIndex = 1;
var totalCount = 21;
setInterval(function() {
if (currentIndex > totalCount)
currentIndex = 1;
$(body).css('background-image', 'url(/bg' + currentIndex++ + '.jpg)');
}, 15000);
<script src="http://codeorigin.jquery.com/jquery-2.0.3.min.js"></script>
<script style="text/javascript">
(function () {
var curImgId = 0;
var numberOfImages = 5; // Change this to the number of background images
window.setInterval(function() {
$('body').css('background','url("'+ curImgId +'.jpg")');// set the image path here
curImgId = (curImgId + 1) % numberOfImages;
}, 15 * 1000);
})();
</script>
精彩评论