<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>随机产生颜色</title>
<style>
div {
width: 200px;
height: 200px;
border-radius:50%;
left: 0;
right:0;
top:0;
bottom: 0;
margin: auto;
position: absolute;
}
</style>
<script>
function getColor() {
var str = "#";
//定义一个十六进制的值的数组
let arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
// 遍历循环产生 6 个数
for (var i = 0; i < 6; i++) {
//随机产生 0~15 的个索引数,然后根据该索引找到数组中对应的值,拼接到一起
let lut = parseInt(Math.random() * 16);
str += arr[lut];
}
return str;
}
window.onload = function () {
//在body中通过id属性的值查找这个元素,设置该标签的背景颜色
setInterval(()=>{
document.getElementById("box").style.backgroundColor = getColor();
},1000)
};
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
随机的颜色,一秒钟切换一个颜色
最新推荐文章于 2024-01-05 10:59:42 发布