1. 初始化数字格

棋盘格初始化实现后,咱们还须要用一个格子来显示数字。

而用来显示数字的格子应该在棋盘格的根底上的,所以初始化数字格的updateBoardView()应该在初始化棋盘格的init()办法的最初来执行。

1.  function init() {2.  //i示意4乘以4的格子的行3.  for(var i=0;i<4;i++){//初始化格子数组4.  //定义了一个二维数组5.  board[i] = new Array();6.  //i示意4乘以4的格子的列7.  for(var j=0;j<4;j++){8.  //初始化小格子的值为09.  board[i][j] = 0;10.  //通过双重遍历获取每个格子元素11.  var gridCell= document.getElementById("grid-cell-" + i + "-" + j)12.  // console.log(gridCell)13.  //通过getPosTop()办法设置每个格子间隔顶端的间隔14.  gridCell.style.top = getPosTop(i, j);15.  //通过getPosLeft()办法设置每个格子间隔左端的间隔16.  gridCell.style.left = getPosLeft(i, j);17.  }18.  }19.  updateBoardView();//告诉前端对board二位数组进行设定。20.  }22.  function updateBoardView() {//更新数组的前端款式24.  }

因为显示数字的格子也是4×4的16个格子,所以咱们间接就和init()办法一样,利用嵌套for循环的形式实现每个数字格的设置。

而后就向棋盘格上减少数字格:

1.  function updateBoardView() {//更新数组的前端款式2.  for (var i = 0; i < 4; i++) {3.  for (var j = 0; j < 4; j++) {4.  //向棋盘格上减少数字格5.  var para=document.createElement("div");6.  para.setAttribute("class", "number-cell")7.  para.setAttribute("id", "number-cell-" + i + "-" + j)8.  var element=document.getElementById("grid-container");9.  element.appendChild(para);10.  }11.  }12.  }

而后再通过判断棋盘的值来设置数字格的高和宽,如果值为0,那么数字格的数字格的高和宽都设置为0,如果值不为0的话,则设置数字格的高和宽并设置背景色和前景色及数字值。

1.  var theNumberCell = document.getElementById('number-cell-' + i + '-' + j)3.  //棋盘的值为0的话,数字格的高和宽都设置为04.  if (board[i][j] == 0) {5.  theNumberCell.style.width = '0rem';6.  theNumberCell.style.height = '0rem';7.  theNumberCell.style.top = getPosTop(i, j);8.  theNumberCell.style.left = getPosLeft(i, j);9.  //棋盘的值不为0的话,则设置数字格的高和宽并设置背景色和前景色及数字值10.  } else {11.  theNumberCell.style.width = '4rem';12.  theNumberCell.style.hegiht = '4rem';13.  theNumberCell.style.top = getPosTop(i, j);14.  theNumberCell.style.left = getPosLeft(i, j);15.  //NumberCell笼罩16.  theNumberCell.style.backgroundcolor = getNumberBackgroundColor(board[i][j]);//返回背景色17.  theNumberCell.style.color = getNumberColor(board[i][j]);//返回前景色18.  theNumberCell.innerHTML = board[i][j];19.  }

保留刷新网页:


图片起源:手游 http://www.diuxie.com/ 手游

这样就实现了数字格的增加以及款式的设置。