使用setInterval更改背景 [英] Change background with setInterval

查看:103
本文介绍了使用setInterval更改背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望页面的背景图像每5秒更改一次.有5张图片,我希望它们循环播放.

I want to have the background image of a page change every 5 seconds. There are 5 images and I want them to loop.

我在这里进行了深入研究,并尝试了不同的方法.有人可以告诉我这段代码有什么问题吗?

I researched thoroughly here and tried different approaches. Can someone please tell me what is wrong with this code:

在我的CSS中,我有:

In my css I have:

html, body, #wrapper {
    height:100%;
    margin: 0;
    padding: 0;
    border: none;
    background-image:url('images/indexbg01.jpg');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center center;
}

和我的JavaScript我有:

and my javascript I have:

var imageArray = ['images/indexbg02.jpg', 'images/indexbg03.jpg', 
                  'images/indexbg04.jpg', 'images/indexbg05.jpg', 
                  'images/indexbg01.jpg'];
var imageIndex = 0;

function changeBgImage(){
    var imageUrl = "url('" + imageArray[imageIndex] + "')";
    $('body').css('background-image', imageUrl);
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
}

setInterval(changeBgImage, 5000);

我首先在下面的代码行中构建了imageUrl变量,但是我添加了它,以便可以检查它是否正常构建. 在chrome调试器中,当我在imageUrl构建行之后的行上放置一个断点时,它每隔5秒钟就会很好地停止一次,就可以构建imageUrl,但背景不会改变.

I first had the imageUrl variable built in the line that follows, but I added this so I could check it was built ok. In the chrome debugger, when I put a breakpoint on the line following the imageUrl build line, it stops nicely every 5 seconds, the imageUrl is built as it should, yet the background does not change.

推荐答案

我编辑了小提琴: http://jsfiddle.net/5Cv49/1/.

输入并查看.唯一的标记是:

Enter and see. The only markup there is the:

<div id="wrapper"></div>

唯一修改的css是:

adding #wrapper to the selector.

查看背景与#wrapper的背景如何重叠.

See how background is overlapped by #wrapper's background.

这篇关于使用setInterval更改背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆