<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>贪吃蛇</title> <style> *{ padding: 0; margin: 0; box-sizing: border-box; } #main{ margin: 100px; } .btn{ width: 100px; height: 40px; /* margin: 10px; */ } .canvas{ position: relative; top: 40px; border: 1px solid rgb(107, 221, 178); background-color: rgb(218, 236, 245); } </style></head><body> <div id="main"> <input class="btn" type="button" value="开始游戏" id="begin"/> <input class="btn" type="button" value="暂停游戏" id="pause"/> <script> var timer; //变量可以提升 var showCanvas = true; //是否显示格子 /*设置地图的构造方法: atom为原子初始化的宽高(应该一致) xnum为地图x轴应该有多少个原子(横向) ynum为地图y轴应该有多少个原子(纵向) */ function Map(atom,xnum,ynum){ this.atom = atom; this.xnum = xnum; this.ynum = ynum; this.canvas = null; //初始化画布 this.create = function(){ this.canvas = document.createElement("div"); this.canvas.className = "canvas"; this.canvas.style.width = this.atom * this.xnum + "px"; //画布的宽 this.canvas.style.height = this.atom * this.ynum + "px"; //画布的高 main.appendChild(this.canvas); if (showCanvas){ for (var i = 0;i<xnum;i++){ for (var j = 0;j<ynum;j++){ //定义格子的样式 var lattice = document.createElement("div"); lattice.style.border = "1px solid rgb(107, 221, 178)"; lattice.style.width = this.atom + "px"; lattice.style.height = this.atom + "px"; //添加格子到地图中 this.canvas.appendChild(lattice); lattice.style.position = "absolute"; //利用绝对定位 lattice.style.left = i * this.atom + "px"; lattice.style.top = j * this.atom + "px"; } } } } } //实例化地图类 var map = new Map(20,40,20); map.create(); //给开始按钮绑定函数 document.querySelector("#begin").onclick = function(){ clearInterval(timer); timer = setInterval(function(){ },300); } document.querySelector("#pause").onclick = function(){ clearInterval(timer); } </script> </div></body></html>