<!DOCTYPE html>
<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>Document</title>
</head>
<body>
<script>
// 生成随机数
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
function getRandomColor(flag = true) {
// 如果参数传递的是true或者无参数,则输出 一个随机十六进制的颜色
if (flag) {
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
// 随机从数组中取出一个数字 取次
// 定义一个字符串
let str = '#' // 字符串拼接
for (let i = 1; i <= 6; i++) {
// 从数组中取出一个数字 当作为数组的下标
const index = getRandom(0, arr.length - 1)
str += arr[index] // str = str + arr[index]
}
return str
} else {
// 返回 rgb() 格式的颜色
let red = getRandom(0, 255)
let green = getRandom(0, 255)
let blue = getRandom(0, 255)
return `rgb(${red},${green},${blue})`
}
}
const res = getRandomColor()
// document.body
// console.log(document.body)
setInterval(function () {
document.body.style.backgroundColor = getRandomColor()
}, 1000)
</script>
</body>
</html>
随机变换页面的背景颜色
最新推荐文章于 2023-12-27 10:09:20 发布