如何使用JavaScript在HTML中随机更改背景颜色?

时间:2012-03-24 21:56:22

标签: javascript html css

此网页随机更改背景颜色。我无法用“#title”做同样的事情,但颜色保持不变。

请帮助

谢谢

JavaScript代码:

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

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

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

    if(index == 1)
        ColorValue = "66FF33"; 
    if(index == 2)
        ColorValue = "FF0000"; 
    if(index == 3)
        ColorValue = "FF00FF"; 
    if(index == 4)
        ColorValue = "0000FF"; 
    if(index == 5)
        ColorValue = "00FFFF"; 
    if(index == 6)
        ColorValue = "FFFF00"; 
    if(index == 7)
       ColorValue = "CC66FF"; 
    if(index == 8)
        ColorValue = "3366FF"; 
   if(index == 9)
        ColorValue = "CCCCCC"; 

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

}

function setbackgroundTitle()
{
    window.setTimeout( "setbackgroundTitle()", 600); //  milliseconds delay

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

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

    if(index == 1)
        ColorValue = "66FF33"; 
    if(index == 2)
        ColorValue = "FF0000"; 
    if(index == 3)
        ColorValue = "FF00FF"; 
    if(index == 4)
        ColorValue = "0000FF"; 


    document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue;

}

CSS代码:

#title{
    background-color:#11f22f;
    height:300px;
    width:400px;
    margin:25px auto 0 auto;
    -moz-border-radius:25px;
    -webkit-border-radius:25px;
}

html代码:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>HomeWork</title>
        <script type="text/javascript" src="crazy.js"> </script>
        <link rel="stylesheet" type="text/css" href="HomeWork2.css" />

    </head>
    <body>

    <body onload="setbackground();">
        <div id="title" onload="setbackgroundTitle();"> hjhjhkj dfvdfsv dfgvkdfsk dfs</div>
    </body>
</html>

4 个答案:

答案 0 :(得分:1)

尝试:

document.getElementById("title").style.backgroundColor = "#" + ColorValue;

答案 1 :(得分:1)

首先,复制粘贴错误:而不是document.getElementById("title")[0].style.backgroundColor = "#" + ColorValue;应该document.getElementById("title").style.backgroundColor = "#" + ColorValue; 据说How to make a div onload function?不起作用。 我把所有东西都放到了setbackground()并且它有效;)

答案 2 :(得分:0)

如果是家庭作业,请将您的问题标记为作业。

否则,jQuery会让你的生活变得如此简单:

$("body").css("background", "#456789");

$("h1").css("background", "#456789");

答案 3 :(得分:0)

问题可能是脚本运行时没有加载DOM。

将此函数更正为此,您假设document.getElementById("title")的输出为数组,但不是。

document.getElementById("title").style.backgroundColor = "#" + ColorValue;

并在onload事件上调用它,以确保在脚本运行时正确加载DOM

window.onload = function() {
 setbackgroundTitle();
};