8x8 div矩阵onclick实现

时间:2019-02-28 22:18:15

标签: javascript html arrays matrix 2d

我希望有一个8x8的矩阵,可以在其中单击每个正方形,并且颜色会发生变化,供项目使用。

我已经制作了一个2d数组和整个8x8“板”,但是现在我想在单击时更改颜色,尽管我能想到的唯一方法是通过沉重的代码,例如编写div [row] [column] 64次...

var div = new Array(8);
for(var i = 0; i<8; i++){
div[i] = new Array(8)
}


for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
    div[i][j] = document.createElement("div");
    div[i][j].style.width = "50px";
    div[i][j].style.height = "50px";
    div[i][j].style.backgroundColor = "white";
    document.getElementById("container").appendChild(div[i][j]);
}
var jump = document.createElement("br");
document.getElementById("container").appendChild(jump);
}

div[0][0].onclick = function(){
if(div[0][0].style.backgroundColor == "white"){
    div[0][0].style.backgroundColor = "red"
    d00 = 1
}
else{div[0][0].style.backgroundColor = "white"
d00 = 0
}
}

我不想写以上64次,肯定有更好的方法。

#container {
margin: auto;
width:400px;
height:400px;
}
#container div {
display:inline-block;
vertical-align:top;
outline: 1px solid black
}

2 个答案:

答案 0 :(得分:0)

确实,有更好的方法。 在for循环内部,您已经在设置DIV的重要属性。这是附加 click eventListener的理想场所,该事件监听器的回调函数将处理颜色切换。

像这样修改for循环:

var divElement;
for (var i = 0; i < 8; i++) {
  for (var j = 0; j < 8; j++) {
    divElement = document.createElement("div");
    divElement.style.width = "50px";
    divElement.style.height = "50px";
    divElement.style.backgroundColor = "white";
    divElement.addEventListener("click", changeColor);
    document.getElementById("container").appendChild(divElement);
  }

并使用此功能实际更改颜色:

function changeColor(e) {
  if (e.target.style.backgroundColor == "white") {
    e.target.style.backgroundColor = "red"
    d00 = 1
  } else {
    e.target.style.backgroundColor = "white"
    d00 = 0
  }
}

e.target 是指触发事件的对象。 原谅我,我不知道 d00 的目的。

答案 1 :(得分:0)

您可以将onclick事件附加到父容器,并使用event.target获取触发事件的div:

document.getElementById("container").onclick = function(event){
  if(event.target.style.backgroundColor == "white"){
    event.target.style.backgroundColor = "red";
  }
  else{
    event.target.style.backgroundColor = "white";
  }
}