<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link href="https://www.jb51.net/demo.css" > </head> <body> <div> <div id = "go">Game Start</div> <!-- 运动的dom --> <div></div> </div> <script src = "demo.js"></script> </body> </html>
CSS:
*{ margin: 0; padding: 0; } .wrapper{ position: relative; width: 400px; height: 600px; border: 1px solid black; margin :160px auto; overflow: hidden; } #go{ position:absolute; left:0; top: 0; width: 100%; height: 100px; border-bottom: 1px solid #000; font-weight: bolder; font-size: 60px; line-height: 100px; text-align: center; cursor: pointer; z-index: 999; } #main{ position: relative; width:400px; height: 600px; /* border:1px solid red; */ } .row{ width: 400px; height: 150px; } .row div{ /* 块级元素水平排列 */ float: left; width: 100px; height: 150px; border: 1px solid #000; /* 混杂模式盒模型 */ box-sizing: border-box; /* 最终显示宽度为设定宽度 */ }
js:
// bindEvent显示开始,清除 creatDiv增加一行 move运动 判断胜负 计分 var go = document.getElementById('go'); // 运动趋于 var main = document.getElementById('main'); var timer; var speed = 5,num = 0,flag = true; function bindEvent() { go.addEventListener('click', function () { go.style.display = 'none'; move(); }); main.addEventListener('click',function(e){ if(flag){ var tar = e.target; if(tar.className == 'tar'){ tar.style.backgroundColor = '#bbb'; tar.classList.remove('tar'); num++; }else{ clearInterval(timer); alert('游戏结束吧得分'+num); flag = false; } } }); } bindEvent(); function move() { timer = setInterval(function(){ // 初始位置+速度 var step = parseInt(main.offsetTop)+speed; // 当前位置付给新的top main.style.top = step+'px'; if(parseInt(main.offsetTop)>=0){ main.style.top = '-150px'; cDiv(); } // 移除多余的div var len = main.childNodes.length; if(len == 6){ var lastRow = main.childNodes[len -1]; // 是否结束 for(var i = 0;i<4;i++){ if(lastRow.childNodes[i].classList.contains('tar')){ clearInterval(timer); alert('游戏结束得分:'+num); flag = false; }} main.removeChild(main.childNodes[len - 1]); } } ,20 ); } // 创建行和列 function cDiv() { // 生成数组颜色 var color = ['red','blue','green','pink']; // 创建一个行 var oDiv = document.createElement('div'); // 生成一个随机数 var index = Math.floor(Math.random()*4); // 创建四列 for (var i = 0; i < 4; i++) { // 创建四个列块 var iDiv = document.createElement('div'); // 行里面插入列 oDiv.appendChild(iDiv); } // 被点击的div var clickDiv = oDiv.childNodes[index]; clickDiv.setAttribute('class','tar'); // 颜色随机 clickDiv.style.backgroundColor = color[index]; oDiv.setAttribute('class', 'row'); // 如果行为空则插入,如果不为空则向上插入; if (main.childNodes.length == 0) { main.appendChild(oDiv); } else { main.insertBefore(oDiv, main.childNodes[0]); } }