<!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>
/*设置页面div的样式*/
div {
width: 200px;
height: 200px;
background: yellow;
/* background: rgb(10, 20, 30); */
}
</style>
<script>
window.onload = function () {//等待页面元素加载完成
function randomColor(type) {//定义函数,设置一个参数。
var str1 = "#";
var str2 = "0123456789abcdef";//十六进制所需的字符,
var str3 = "rgb(" //rgb的格式;
var str4 = "";//统一返回值
if (type == 16) { //判断参数
for (var i = 0; i < 6; i++) { //循环6次
var n = parseInt(Math.random() * str2.length);
str1 += str2[n];//拼接
}
str4 = str1;//统一返回值
}
if (type == "rgb") {//判断参数
for (var i = 0; i < 3; i++) {//循环三次
var n = parseInt(Math.random() * 255) + 1;//获取0-255中的随机数,因为rgb的方式是有三位0-255数字组成的
if (i != 2) {
str3 += n + ",";//拼接
} else {
str3 += n;//第三位后面没有逗号
}
}
str3 += ")";
//console.log(str3);
str4 = str3;//统一返回值
}
// return str3;
// return str1;
return str4; //返回
}
btn1.onclick = function () {//点击事件
var btn1 = document.getElementById("btn1");//获取元素
var btn11 = btn1.value;//获取元素值
// console.log(btn11);
var val = randomColor(btn11);//传进参数并接收
console.log(val);//打印在控制台
box.style.backgroundColor = val;//设置样式
}
//同上
btn2.onclick = function () {
var btn2 = document.getElementById("btn2");
var btn22 = btn2.value;
//console.log(btn22);
var val = randomColor(btn22);
console.log(val);
box.style.backgroundColor = val;
}
}
</script>
</head>
<body>
<input type="button" id="btn2" value="rgb">
<input type="button" id="btn1" value="16">
<div id="box"></div>
</body>
</html>
付明旭