接着昨天的随机颜色,今天在页面放一个div和一个button,欲实现:click on button时,div换随机背景颜色;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>randomColor</title>
<style>
div{
margin:200px auto 0 auto;
border:3px solid #ddd;
width:300px;
height:300px;
position: relative;
}
</style>
</head>
<body>
<div></div>
<button>点我</button>
<script>
function $(selector){
return document.querySelector(selector);
}
function randomColor(){
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
return "r"+"g"+"b("+r+","+g+","+b+")";
}
$("button").onclick=function(){
$("div").style.background=randomColor();
}
</script>
</body>
</html>
在randomColor(),也可以传参数,生成一定颜色;
function randomColor(min,max){
var r=Math.floor(Math.random()*(max-min)+min);
var g=Math.floor(Math.random()*(max-min)+min);
var b=Math.floor(Math.random()*(max-min)+min);
return "r"+"g"+"b("+r+","+g+","+b+")";
}
比如,randomColor(200,256)会生成浅色;
randomColor(0,100)会生成深色;