How do I make my background change images automatically every 15 seconds? JavaScript? jQuery?

后端 未结 3 2099
小蘑菇
小蘑菇 2021-02-06 19:06

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 automatically. (lik

相关标签:
3条回答
  • 2021-02-06 19:10

    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);
    
    0 讨论(0)
  • 2021-02-06 19:27
    <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>
    
    0 讨论(0)
  • 2021-02-06 19:32

    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);
    })();
    
    0 讨论(0)
提交回复
热议问题