随机生成10000个颜色值渲染到网页上。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="colors"></div>
<script>
;(function(param) {
// 首先创建需要颜色值
let arr = Array(10)
.fill(0)
.map((_, index) => index.toString())
arr = arr.concat(['a', 'b', 'c', 'd', 'd', 'e', 'f'])
// 创建生成颜色的函数
function generatColor(arr) {
let str = '#'
for (let i = 0, len = 6; i < len; i++) {
str += arr[~~(Math.random() * arr.length)]
}
return str
}
// 获取需要在 dom 创建演示的节点
const colorsDom = document.getElementById('colors')
// 创建 dom 片段提高渲染性能
const domFragment = document.createDocumentFragment()
// 产生10000个颜色值
for (let i = 0, len = 10000; i < len; i++) {
const dom = document.createElement('DIV')
dom.width = 100
dom.height = 100
dom.style.cssText = `display: inline-block; width: 100px; height: 100px; margin-right: 5px; background-color: ${generatColor(
arr
)}`
// 添加每个颜色值节点到 dom 片段
domFragment.appendChild(dom)
}
// 添加每个颜色片段到演示节点
colorsDom.appendChild(domFragment)
})()
</script>
</body>
</html>