需求:点击按钮随机给盒子换背景色
用到的知识点:Math.random Math.round
文章地址 https://www.cnblogs.com/sandraryan/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{text-align: center;}
#box {
width: 100px;height: 100px;margin: 10px auto;
border: 1px solid green; border-radius: 8px;
}
button{
padding: 5px; border-radius: 4px;
}
</style>
</head>
<body>
<button id="btn">click me</button>
<div id="box">box</div>
<script>
var btn = document.getElementById("btn");
var box = document.getElementById("box");
// 获取需要的元素
btn.onclick = function(){
// 绑定点击事件
var color1 = Math.round(Math.random()*255);
var color2 = Math.round(Math.random()*255);
var color3 = Math.round(Math.random()*255);
// 获取三个值作为rgb值,random只能在0-1范围内随机,乘255就好了
// 要取整数所以四舍五入round
var mix = "rgb(" + color1 + "," + color2 +"," + color3 + ")";
// 把三个颜色的值拼接在一起
box.style.backgroundColor = mix;
// 改变颜色背景色为刚才获取的值
}
</script>
</body>
</html>