Jquery,用计时器改变背景图像

时间:2014-02-27 17:10:46

标签: jquery image background

我有两个背景图片我正在使用这个网站,我希望它们每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]);
});

1 个答案:

答案 0 :(得分:25)

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

以下是已修复的修订版: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]);
});