css部分
body{
taxt-align:center;
}
#box{
margin: 100px auto 0;
}
#btn{
width: 100px;height: 50px;
}
html部分
<div id="box"></div>
<button id="btn">变色</button>
JS 部分
<script>
function get(id) {
return document.getElementById(id);
}
get("box").style.width = "500px";
get("box").style.height = "500px";
get("box").style.background = "blue";
get("btn").onclick = function () {
box.style.background = randomColor();
};
function randomColor() {
var col = "rgb(";
for(var i = 0;i < 3;i++){
col += Math.floor(Math.random()*256)+",";
}
col = col.slice(0,-1);//rgb( 会多出一个 , 将它舍弃;
col += ")"; //加上 ) 得到 rgb(***,***,***);
return col;
}
</script>