展示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4ee2759ebe1b474283914d83aeda842f.gif)
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>
<link rel="stylesheet" href="../css/test4.css">
</head>
<body>
<div class="wapper">
<div id="go">
<a href="#">Game Start</a>
</div>
<div id="main"></div>
</div>
</body>
<script src="../js/my.js"></script>
</html>
css部分:
* {
margin: 0;
padding: 0;
text-decoration:none;
}
.wapper{
overflow: hidden;
position: relative;
width:400px;
height:600px;
margin:150px auto;
border:1px solid black;
}
.wapper #go{
width:100%;
border-bottom: 1px dashed black;
position: absolute;
top:0px;
text-align: center;
z-index: 100;
}
.wapper #go a{
font-size:60px;
color:cyan;
}
.wapper #main{
position: relative;
top:-100px;
width:100%;
height:100%;
}
#odiv{
height:150px;
width:100%;
}
#idiv{
float:left;
height:149px;
width:99px;
border-bottom: 1px solid black;
border-right:1px solid black;
}
javascript部分:
var go = document.getElementById("go");
var main = document.getElementById("main");
var timer, num,
speed,
flag;
function init() {
go.addEventListener("click", function () {
main.innerHTML = "";
num = 0;
speed = 5;
flag = true;
go.style.display = "none";
move();
});
}
function move() {
clearInterval(timer);
timer = setInterval(function () {
main.style.top = main.offsetTop + speed + "px";
if (main.offsetTop > 0) {
main.style.top = "-150px";
CDiv();
var len = main.childNodes.length;
if (len > 5) {
if (main.childNodes[len - 1].className == "color") {
alert("游戏结束:得分为" + num);
clearInterval(timer);
go.style.display = "block";
flag = false;
} else {
main.removeChild(main.childNodes[len - 1]);
}
}
}
}, 20);
}
function CDiv() {
var odiv = document.createElement("div");
odiv.setAttribute("id", "odiv");
odiv.setAttribute("class", "color");
var index = Math.floor(Math.random() * 4);
for (var i = 0; i < 4; i++) {
var idiv = document.createElement("div");
idiv.setAttribute("id", "idiv");
odiv.appendChild(idiv);
if (i == index) {
idiv.style.backgroundColor = "black";
idiv.addEventListener("click", function () {
if (flag) {
this.style.backgroundColor = "#bbb";
odiv.removeAttribute("class", "color");
num++;
if(num%5==0){
speed++;
}
}
})
} else {
idiv.addEventListener("click", function () {
if (flag) {
alert("游戏结束:得分为" + num);
clearInterval(timer);
go.style.display = "block";
flag = false;
}
})
}
}
if (main.childNodes.lenth == 0) {
main.appendChild(odiv);
} else {
main.insertBefore(odiv, main.childNodes[0]);
}
}
init();