今天我们来做一个JS变色药丸,每次刷新网页随机变色
原理:
- 药丸的两部分分别采用16进制颜色编码和rgb颜色编码
- 创建两种编码的数组
- 利用Math.floor(Math.random() * color_arr.length)抽取数组随机元素
- 再利用模版字符串将盒子写入DOM。
效果如下:

代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
width: 100px;
height: 100px;
margin: 0 auto;
}
div:nth-of-type(1) {
border-radius: 50% 50% 0 0;
}
div:nth-of-type(2) {
border-radius: 0 0 50% 50%;
}
</style>
<body>
<script>
// 1.获取16进制颜色编码函数
createColor_16 = function () {
let color_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']
sum = '#'
for (let i = 0; i < 6; i++) {
randomNum = Math.floor(Math.random() * color_arr.length)
sum += color_arr[randomNum]
}
return sum
}
// 2.获取rgb颜色编码函数
createColor_rgb = function () {
let numArr = []
for (let i = 0; i < 3; i++) {
getNum = Math.floor(Math.random() * 256)
// 储存生成数组
numArr.push(getNum)
}
console.log(numArr)
return `rgb(${numArr[0]}, ${numArr[1]}, ${numArr[2]})`
}
// 颜色渲染16进制颜色盒子
document.write(`
<div style = "background-color: ${createColor_16()};"></div>
`)
// 颜色渲染16进制颜色盒子
document.write(`
<div style = "background-color: ${createColor_rgb()};"></div>
`)
</script>
</body>
</html>

被折叠的 条评论
为什么被折叠?



