新建文本文档,复制下面的代码,保存,文件名:index.html,打开
<!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>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
font-family: '隶书';
}
h1 {
line-height: 50px;
}
.box {
width: 525px;
margin: 25px 0 0 25px;
padding: 15px;
text-align: center;
line-height: 500px;
border: solid 1px black;
overflow: hidden;
}
.box h1 {
text-align: left;
}
.box .item {
box-sizing: border-box;
width: 95px;
height: 95px;
margin: 5px;
float: left;
line-height: 95px;
border: solid 1px black;
font-size: 23px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<h1>Hi</h1>
</div>
<script>
let log = console.log.bind(console),
eBox = document.querySelector('.box'),
aColor = [],
aIndex = [],
eCurrent = '',
nCurrent = ''
let randomColor = function() {
return "rgb(" + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ");"
}
for (let i = 0; i < 10; i++) {
aColor.push(randomColor())
aIndex.push(i)
aIndex.push(i)
}
for (let i = 0; i < 20; i++) {
let eDiv = document.createElement('div'),
num = Math.floor(Math.random() * aIndex.length)
eDiv.className = 'item'
eDiv.innerHTML = aIndex[num]
eDiv.setAttribute('index', aIndex[num])
eBox.appendChild(eDiv)
aIndex.splice(num, 1)
}
let aItem = document.querySelectorAll('.item')
for (let i = 0; i < aItem.length; i++) {
aItem[i].onclick = function() {
if (this.getAttribute('index') == nCurrent && eCurrent != this) {
this.innerHTML = ''
eCurrent.innerHTML = ''
} else {
nClick = this.getAttribute('index')
eCurrent = this
}
nCurrent = this.getAttribute('index')
}
}
</script>
</body>
</html>