Javascript 如何更改网格中我单击的框旁边的框的颜色
我有一个5x5网格,只要你点击它,每个框都可以变成黑色或白色。这个网格模拟熄灯游戏,到目前为止,我只能更改我正在单击的框的颜色,但我还需要更改框的颜色水平和垂直距离为1 我有一种感觉,我需要使用javascript将网格变成一个数组,但我不知道如何做到这一点。下面的代码是我到目前为止的代码Javascript 如何更改网格中我单击的框旁边的框的颜色,javascript,html,Javascript,Html,我有一个5x5网格,只要你点击它,每个框都可以变成黑色或白色。这个网格模拟熄灯游戏,到目前为止,我只能更改我正在单击的框的颜色,但我还需要更改框的颜色水平和垂直距离为1 我有一种感觉,我需要使用javascript将网格变成一个数组,但我不知道如何做到这一点。下面的代码是我到目前为止的代码 var grid=document.getElementsByClassName(“框”); Array.from(grid).forEach(单击=>click.addEventListener(“单击”
var grid=document.getElementsByClassName(“框”);
Array.from(grid).forEach(单击=>click.addEventListener(“单击”,函数changeColor()){
如果(单击.style.background==='black'){
单击.style.background=“白色”;
}否则{
单击.style.background=“黑色”;
}
}));代码>
正文{
背景颜色:浅蓝色;
利润率:40像素;
}
.包装纸{
显示:网格;
网格模板列:100px 100px 100px 100px 100px 100px;
网格间距:3倍;
}
.盒子{
背景色:#fff;
填充:50px;
}
熄灯游戏
熄灯
复位板
单击每个框,直到所有框都变黑。
由于单击操作将通过调用changeColor
影响多个框,因此最好将其与事件侦听器分开
const changeColor = function(box){
if (box.style.background === 'black') {
box.style.background = "white";
} else {
box.style.background = "black";
}
}
您仍然需要分配一个事件处理程序,我们将创造性地调用clickHandler
Array.from(grid).forEach(box => click.addEventListener("click", () => clickHandler(box)))
区分每个盒子会很有用;这可以通过为它们中的每一个添加id
属性来完成,同时还可以分配侦听器,使上面的行变为
Array.from(grid).forEach(
(box, index) => {
box.addEventListener("click", () => clickHandler(box))
box.id = index
}
)
最后,您需要确定单击某个框时需要更改哪些框。这可以在clickHandler
函数中定义
let boxes = Array.from(grid)
const clickHandler= function(box){
// get the box id, which will coincide with its position in the array
index = parseInt(c.id)
// determine the adjacent boxes' indexes
up = index - 5
down = index + 5
left = index - 1
right = index + 1
// Make sure the index is not out of bounds and change color
if(up > 0)
changeColor(boxes[up])
if(down < 25)
changeColor(boxes[down])
// Make sure the left and right indexes are in the same row
if(Math.floor(index / 5) == Math.floor(left / 5))
changeColor(boxes[left])
if(Math.floor(index / 5) == Math.floor(right / 5))
changeColor(boxes[right])
// change the color of the box that was clicked
changeColor(boxes[index])
}
熄灯游戏
熄灯
复位板
单击每个框,直到所有框都变黑。