效果图
![](https://i-blog.csdnimg.cn/direct/396b2767716443b38102b391a74f6529.png)
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>练习:生成随机颜色</title>
<style>
body {
display: flex;
}
div {
position: relative;
margin: 20px;
width: 150px;
height: 150px;
}
div span {
position: absolute;
bottom: -30px;
}
</style>
</head>
<body>
<script>
function getColor(flag = true) {
if (flag) {
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
let randomColor = '#'
for (let i = 0; i < 6; i++) {
randomColor += arr[Math.floor(Math.random() * arr.length)]
}
return randomColor
} else {
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
}
document.write(`
<div style="background-color: ${getColor()};">
<span>${getColor()}</span>
</div>
<div style="background-color: ${getColor(false)};">
<span>${getColor(false)}</span>
</div>
`)
</script>
</body>
</html>