此網頁隨機更改背景顏色。我很難用「#title」做同樣的事情,但顏色保持不變。如何用JavaScript隨機更改背景顏色?
請幫助
謝謝
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>
將來,考慮使用匿名函數而不是'setTimeout'的字符串。 'setTimeout(function(){setbackgroundTitle()},600);'就足夠了。 – 2012-03-24 21:58:41
__常規代碼提示:__如果你有幾個像這樣的if語句,它們都會每次都運行,即使索引是1.使用switch語句代替。或者在這種情況下,更好的解決方案是將所有顏色值存儲在數組中,並使用myColorArray [index]來獲取您的值。 – 2012-03-24 23:52:22
這是一樣的http://stackoverflow.com/questions/25455485/how-change-background-color-of-html-elements-with-javascript-in-a-certain-time-p/25455719#25455719 – 2014-08-27 21:45:01