繁体   English   中英

每5秒随机生成一次背景图片?

[英]Random background image every 5 seconds?

我基本上找到了此代码,并尝试对其进行了一些更改。 我尝试使用图像代替颜色,但是效果不是很好。 我已经检查了其他类似的问题,但是无论如何,它并没有给我一直在寻找的帮助。

正如您在代码中看到的那样,它每隔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();">

您可以这样操作:

  <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();">

这是一种简单的方法:

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是图像url的数组,而targetId是要更改其background-image属性的容器的ID。

JSFiddle上的示例 (带有小猫)

- 编辑 -

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

-编辑2--

我重新阅读了您的问题,看来您想更改正文的背景图像。 上面的功能(和JSFiddle中的功能)适用于目标ID。 如果要在主体上使用它,则可以为主体指定一个ID,然后以主体的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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM