每5秒随机背景图像?

时间:2014-08-19 17:55:29

标签: javascript image random colors

我基本上发现了这段代码,我试着改变它。我尝试使用图像而不是颜色,但效果并不好。我已经检查了其他类似的问题,但无论如何它并没有给我提供所需的帮助。

正如你在代码中看到的,它每5000毫秒随机改变backgroundColor,我想知道如何让它随机改变图片(背景图片)而不是颜色?

<script type="text/javascript">

function setbackground()
{
window.setTimeout( "setbackground()", 5000); // 5000 milliseconds delay

var index = Math.round(Math.random() * 9);

var ColorValue = "FFFFFF"; // default color - white (index = 0)

if(index == 1)
ColorValue = "FFCCCC"; //peach
if(index == 2)
ColorValue = "CCAFFF"; //violet
if(index == 3)
ColorValue = "A6BEFF"; //lt blue
if(index == 4)
ColorValue = "99FFFF"; //cyan
if(index == 5)
ColorValue = "D5CCBB"; //tan
if(index == 6)
ColorValue = "99FF99"; //lt green
if(index == 7)
ColorValue = "FFFF99"; //lt yellow
if(index == 8)
ColorValue = "FFCC99"; //lt orange
if(index == 9)
ColorValue = "CCCCCC"; //lt grey

document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;

}
</script>
<body onload="setbackground();">

2 个答案:

答案 0 :(得分:0)

你可以这样做:

  <script type="text/javascript">

function setbackground()
{
window.setTimeout( "setbackground()", 5000); // 5000 milliseconds delay

var index = Math.round(Math.random() * 9);

var ImagePath = "image0.jpg"; // default image

if(index == 1)
ImagePath = "image1.jpg"; 
if(index == 2)
ImagePath = "image2.jpg";
if(index == 3)
ImagePath = "image3.jpg";
if(index == 4)
ImagePath = "image4.jpg";
if(index == 5)
ImagePath = "image5.jpg"; 
if(index == 6)
ImagePath = "image6.jpg"; 
if(index == 7)
ImagePath = "image7.jpg"; 
if(index == 8)
ImagePath = "image8.jpg"; 
if(index == 9)
ImagePath = "image9.jpg"; 

document.getElementsByTagName("body")[0].style.backgroundImage="url('"+ ImagePath+ "')"

}
</script>
<body onload="setbackground();">

答案 1 :(得分:0)

这是一种简单的方法:

function setBackground(urls, targetId) {
    setInterval(function() {
        var index = Math.floor(Math.random() * (urls.length));
        var target = document.getElementById(targetId);
        target.style.backgroundImage = "url(" + urls[index] + ")";

    }, 5000);
}

其中urls是一个图片网址数组,而targetId是您想要更改background-image属性的容器的ID。

Example on JSFiddle(与小猫一起)

- 编辑 -

请记住,在加载新图像时,背景(背景图像后面)是可见的。为了说明这一点,我将background-color设置为红色。当一个新的图像开始加载时,你会看到一个红色的闪光(具有讽刺意味的小猫主题)。

- 编辑2 -

我重读了你的问题,看起来你想要改变身体的背景图像。上面的函数(以及JSFiddle中的函数)对目标ID起作用。如果你想在身体上使用它,你可以给你的身体一个id并运行身体的功能&#39; id作为参数。或者您可以使用它:

function setBackground(urls) {
    setInterval(function() {
        var index = Math.floor(Math.random() * (urls.length));
        var target = document.getElementsByTagName("body")[0];
        target.style.backgroundImage = "url(" + urls[index] + ")";

    }, 5000);
}
相关问题