封装一个获取随机颜色的函数
要求:该函数接收一个布尔类型参数,表示颜色的格式是十六进制还是rgb格式
- @description:获取随机颜色
- @param {type} flag:布尔类型 true: 十六进制颜色 false:rgb格式颜色
- @return: 随机颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: auto;
float: left;
margin-right: 20px;
font-size: 36px;
line-height: 300px;
text-align: center;
}
</style>
</head>
<body>
<div class="one">十六进制</div>
<div class="two">RGB</div>
<script>
function getRandomColor(flag) {
if (flag) {
let str = '';
for (var i = 0; i < 6; i++) {
str += Math.floor(Math.random() * 16).toString(16);
}
return '#' + str.toLowerCase()
} else {
let r = parseInt(Math.random() * 256)
let g = parseInt(Math.random() * 256)
let b = parseInt(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
};
let one = document.querySelector('.one');
let two = document.querySelector('.two');
one.style.background = getRandomColor(true);
two.style.background = getRandomColor(false);
console.log(getRandomColor(true)); //#fabc12
console.log(getRandomColor(false)); //rgb(128,65,88)
</script>
</body>
</html>
- toString(16); 进制转换为16进制
- Math.floor() 返回小于或等于一个给定数字的最大整数。
Note: Math.floor() === 向下取整 - Math.random() 函数返回一个浮点, 伪随机数在范围[0,1)