出处链接:http://www.5code.net
var arr = ["yellow","pink","green","orange","blue","#ccc","#ddd","black","#c00","#d122b2","#78336c","#0461a2","#d9764f","#1bae17","#13b5c4","#a100fe","red"];
以上是收集自己喜欢的颜色.
for(var i=0; i<arr.length; i++){
colors.style.background= arr[Math.floor(Math.random() * (17+1))];
}
然后遍历这些颜色,让colors.style.background等于随机循环的arr[i].
最后通过setInterval方法重复执行randomChangeBG()函数里面的代码.
整体代码:
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta content ="text/html; charset=gb2312" http-equiv ="Content-Type" >
< title > 无标题文档 </ title >
< style type ="text/css" >
#colors { position : absolute ; left : 50% ; top : 50% ; border : 1px solid green ; width : 200px ; height : 150px ; margin-left : -100px ; margin-top : -75px ; line-height : 150px ; text-align : center }
</ style >
</ head >
< body >
< div id ="colors" >
深蓝色梦想
</ div >
< script type ="text/javascript" >
var t;
var colors = document.getElementById( " colors " );
function randomChangeBG(){
var arr = [ " yellow " , " pink " , " green " , " orange " , " blue " , " #ccc " , " #ddd " , " black " , " #c00 " , " #d122b2 " , " #78336c " , " #0461a2 " , " #d9764f " , " #1bae17 " , " #13b5c4 " , " #a100fe " , " red " ];
for ( var i = 0 ; i < arr.length; i ++ ){
colors.style.background = arr[Math.floor(Math.random() * ( 17 + 1 ))];
}
}
t = setInterval( " randomChangeBG() " , 100 );
colors.onmouseover = function (){
clearInterval(t)
}
colors.onmouseout = function (){
t = setInterval( " randomChangeBG() " , 100 );
}
</ script >
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta content ="text/html; charset=gb2312" http-equiv ="Content-Type" >
< title > 无标题文档 </ title >
< style type ="text/css" >
#colors { position : absolute ; left : 50% ; top : 50% ; border : 1px solid green ; width : 200px ; height : 150px ; margin-left : -100px ; margin-top : -75px ; line-height : 150px ; text-align : center }
</ style >
</ head >
< body >
< div id ="colors" >
深蓝色梦想
</ div >
< script type ="text/javascript" >
var t;
var colors = document.getElementById( " colors " );
function randomChangeBG(){
var arr = [ " yellow " , " pink " , " green " , " orange " , " blue " , " #ccc " , " #ddd " , " black " , " #c00 " , " #d122b2 " , " #78336c " , " #0461a2 " , " #d9764f " , " #1bae17 " , " #13b5c4 " , " #a100fe " , " red " ];
for ( var i = 0 ; i < arr.length; i ++ ){
colors.style.background = arr[Math.floor(Math.random() * ( 17 + 1 ))];
}
}
t = setInterval( " randomChangeBG() " , 100 );
colors.onmouseover = function (){
clearInterval(t)
}
colors.onmouseout = function (){
t = setInterval( " randomChangeBG() " , 100 );
}
</ script >
</ body >
</ html >