代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生成随机颜色</title>
<style>
div {
width: 100px;
height: 100px;
margin: 100px auto;
border: 1px #777 solid;
position: relative;
}
button {
position: absolute;
bottom: -50px;
left: 0;
}
</style>
</head>
<body>
<div><button>生成随机颜色</button></div>
<script>
var randomColor = function (obj) {
var random = function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
//random(min,max) 向下取整的随机数
}
var r=random(0,255)
var g=random(0,255)
var b=random(0,255)
obj.style.backgroundColor="rgb("+r+",+"+g+","+b+")"
}
var box=document.querySelector("div")
var button=document.querySelector("button")
button.onclick=function(){
randomColor(box)
}
</script>
</body>
</html>
效果展示:
点击之后
再次点击
生成一个向下取整的随机数
return Math.floor(Math.random() * (max - min)) + min;
//random(min,max) 向下取整的随机数
}
生成3个0-255之间的数rgb(r,g,b),改变div的颜色
var random = function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
//random(min,max) 向下取整的随机数
}
var r=random(0,255)
var g=random(0,255)
var b=random(0,255)
obj.style.backgroundColor="rgb("+r+",+"+g+","+b+")"
}