Jquery,使用计时器更改背景图像

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

Jquery, changing background image with timer

jqueryimagebackground

提问by Joseph Montecalvo

I have two background images I am using for this website and I want them to change automatically every 5 seconds. Can someone please look at my jQuery code and tell me what I am doing wrong?

我有两个用于此网站的背景图像,我希望它们每 5 秒自动更改一次。有人可以看看我的 jQuery 代码并告诉我我做错了什么吗?

$(function() {
    var body = $(‘body');
    var backgrounds = new Array(
        ‘url(images/hso-palmtree-background.jpg)',
        ‘url(images/hso-boardwalk-background.jpg)'
    );

    var current = 0;

    function nextBackground() {
        body.css(
           ‘background',
            backgrounds[current = ++current % backgrounds.length]
        );

        setTimeout(nextBackground, 5000);
    }

    setTimeout(nextBackground, 5000);
    body.css(‘background', backgrounds[0]);
});

回答by Majid Fouladpour

You code is correct, you just need to change the backticks. Change to '.

你的代码是正确的,你只需要改变反引号。更改'

Here is a cleaned revision: http://jsfiddle.net/X2NqX/

这是一个干净的修订版:http: //jsfiddle.net/X2NqX/

$(function () {
    var body = $('body');
    var backgrounds = [
      'url(http://static.jsbin.com/images/jsbin_static.png)', 
      'url(http://static.jsbin.com/images/popout.png)'];
    var current = 0;

    function nextBackground() {
        body.css(
            'background',
        backgrounds[current = ++current % backgrounds.length]);

        setTimeout(nextBackground, 5000);
    }
    setTimeout(nextBackground, 5000);
    body.css('background', backgrounds[0]);
});