如何让我的背景每 15 秒自动更改一次图像?JavaScript?jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6808072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:55:58  来源:igfitidea点击:

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

javascriptjquerycss

提问by Fab

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

我知道这听起来很简单,我在网上上下搜索了一个脚本,但找不到任何东西。我只希望我的背景每 15 秒左右自动更改一次。(就像照片幻灯片,但作为背景。)我的样式表控制 body 标签中的 bg 图像。谢谢您的帮助。

回答by phihag

With setInterval, you can call an arbitrary function in, well, intervals:

使用setInterval,您可以在时间间隔内调用任意函数:

(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);
})();

回答by Kon

Simple enough to do with setInterval:

使用setInterval 很简单:

var currentIndex = 1;
var totalCount = 21;

setInterval(function() {
    if (currentIndex > totalCount)
        currentIndex = 1;

    $(body).css('background-image', 'url(/bg' + currentIndex++ + '.jpg)');
}, 15000);

回答by user2676376

<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>