使用 jQuery 更改正文背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18723103/
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-08-26 22:19:03  来源:igfitidea点击:

Change body background image with jQuery

javascriptjqueryhtmlcss

提问by Callum

I decided to make a function that changes the body background image after every 10 seconds.

我决定制作一个每 10 秒改变一次身体背景图像的函数。

function Background()
{
    var Background_Stage;
    switch(Background_Stage)
    {
        case 0:
        {
            $('body').css.('background', '#000 url(../../Styles/Callum_Project1/Images/BACKGROUND_1_TEST.png) no-repeat');
            Background_Stage++;
            setInterval(function(){Background()},10000);
        }
        case 1:
        {
            $('body').css.('background', '#000 url(../../Styles/Callum_Project1/Images/BACKGROUND_2_TEST.png) no-repeat');
            Background_Stage++;
            setInterval(function(){Background()},10000);
        }
        case 2:
        {
            $('body').css.('background', '#000 url(../../Styles/Callum_Project1/Images/BACKGROUND_2_TEST.png) no-repeat');
            Background_Stage = 0;//Reset 
            setInterval(function(){Background()},10000);
        }
    }
}

However hen I did something like this

然而,当我做了这样的事情

<body onload="Background()"></body>

It doesn't seem to do anything, this might be a dumb thing to ask for help with but this is the first I did when I was learning JavaScript, I should say that I used jQuery for most of this.

它似乎没有做任何事情,寻求帮助可能是一件愚蠢的事情,但这是我在学习 JavaScript 时做的第一件事,我应该说我在其中大部分时间都使用了 jQuery。

回答by Ben Hymanson

There's a few problems with your code:

您的代码存在一些问题:

  • The value of Background_Stage won't persist between calls to Background, and in any case, you never assign a value to Background_Stage.
  • Use setTimeout rather than setInterval. setTimeout will call the function once at the end of the allotted time. setInterval will keep calling the same function again and again until explicitly cancelled. The way you have it, you'll end up with lots of concurrent setIntervals running.
  • You don't need the '.' between css and the following parenthesis.
  • Background_Stage 的值不会在对 Background 的调用之间保持不变,并且在任何情况下,您都不会为 Background_Stage 分配值。
  • 使用 setTimeout 而不是 setInterval。setTimeout 将在分配的时间结束时调用该函数一次。setInterval 将一次又一次地调用相同的函数,直到明确取消。按照您的方式,您最终会运行大量并发 setIntervals。
  • 你不需要'.' 在 css 和以下括号之间。

Finally, try not to repeat yourself, meaning that if you find yourself typing out more or less the same statements over and over, then you can probably make the code cleaner. Something like:

最后,尽量不要重复自己,这意味着如果您发现自己一遍又一遍地输入或多或少相同的语句,那么您可能可以使代码更清晰。就像是:

(function() 
{
    var bgCounter = 0,
        backgrounds = [
           "../../Styles/Callum_Project1/Images/BACKGROUND_1_TEST.png",
           "../../Styles/Callum_Project1/Images/BACKGROUND_2_TEST.png",
           "../../Styles/Callum_Project1/Images/BACKGROUND_3_TEST.png"
        ];
    function changeBackground()
    {
        bgCounter = (bgCounter+1) % backgrounds.length;
        $('body').css('background', '#000 url('+backgrounds[bgCounter]+') no-repeat');
        setTimeout(changeBackground, 10000);

    }
    changeBackground();
})();

Now changing the background URLs or adding more is a simple job of editing the backgrounds array.

现在更改背景 URL 或添加更多是编辑背景数组的简单工作。

回答by Manu Goel

You can also try this:

你也可以试试这个:

function Background(){
    var imgs = [
            "../../Styles/Callum_Project1/Images/BACKGROUND_1_TEST.png",
            "../../Styles/Callum_Project1/Images/BACKGROUND_2_TEST.png",
            "../../Styles/Callum_Project1/Images/BACKGROUND_3_TEST.png"
        ],
        len = imgs.length,
        idx = -1;

    setInterval(function(){
        idx = (idx+1)%len;
        $("body").css("background", "#000 url("+imgs[idx]+")");
    }, 10000);
}

回答by Quentin

Every time you call background, you instantiate a new localvariable called Background_Stagewith a value of undefined. This doesn't match any of your switchoptions.

每次调用后台的时候,你实例化一个新的地方叫做变量Background_Stage具有的价值undefined。这与您的任何switch选项都不匹配。

You need to declare the variable outside of your function (so it persists between calls to the function) and give it a starting value.

您需要在函数外部声明变量(因此它在函数调用之间保持不变)并为其指定一个起始值。

回答by user2736012

  • Your Backgroud_Stageis not initialized
  • Your setIntervalplacement will cause very serious problems
  • There's also invalid syntax.
  • Backgroud_Stage的未初始化
  • 你的setInterval安置会导致非常严重的问题
  • 还有无效的语法。

Overall, your code can be simpler like this:

总的来说,您的代码可以像这样更简单:

var Stage = 0;
setInterval(function() {
    var bg = '#000 url(../../Styles/Callum_Project1/Images/BACKGROUND_'+(Stage+1)+'_TEST.png) no-repeat';
    document.body.style.background = bg;
    Stage = ++Stage % 3;
}, 10000);