我目前正在尝试使用2D数组。我现在无法想到这样做的方法,但我希望能够单击其中一个单元格并将其更改为相反的颜色。为了演示,如果我单击一个蓝色单元格,我希望它变成红色,如果我单击一个红色单元格则相反。这是我的代码:
<!DOCTYPE html>
<html>
<head><title>Visualizing 2D Arrays</title>
<style>
#stage
{
position: relative;
}
.cell
{
position: absolute;
width: 30px;
height: 30px;
border: 1px solid black;
background-color: blue;
}
</style>
</head>
<body>
<div id="stage"></div>
<script>
//Get a reference to the stage
var stage = document.querySelector("#stage");
//The 2D array that defines the pattern
var pattern =
[
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
];
//The sixe of each cell
var SIZE = 30;
//The space between each cell
var SPACE = 10;
//Display the array
var ROWS = pattern.length;
var COLUMNS = pattern[0].length;
for(var row = 0; row < ROWS; row++)
{
for(var column = 0; column < COLUMNS; column++)
{
//Create a div HTML element called cell
var cell = document.createElement("div");
//Set its CSS class to "cell"
cell.setAttribute("class", "cell");
//Add the div HTML element to the stage
stage.appendChild(cell);
//Make it black if it's a "1"
if(pattern[row][column] === 1)
{
cell.style.backgroundColor = "red";
}
//Position the cell in the correct place
//with 10 pixels of space around it
cell.style.top = row * (SIZE + SPACE) + "px";
cell.style.left = column * (SIZE + SPACE) + "px";
}
}
</script>
</body>
答案 0 :(得分:0)
为了简化问题,添加
else
条件,其中blue
颜色设置为元素。
要使用点击监听器,会使用addEventListener
/ node
element
方法。还有其他方法可以附加点击侦听器。 addEventListener
期望第二个参数是一个回调函数,它是在事件发生click
事件后调用的函数表达式。 element.style.backgroundColor
会将backgroundColor
设置为元素。
var stage = document.querySelector("#stage");
//The 2D array that defines the pattern
var pattern = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
];
//The sixe of each cell
var SIZE = 30;
//The space between each cell
var SPACE = 10;
//Display the array
var ROWS = pattern.length;
var COLUMNS = pattern[0].length;
for (var row = 0; row < ROWS; row++) {
for (var column = 0; column < COLUMNS; column++) {
//Create a div HTML element called cell
var cell = document.createElement("div");
//Set its CSS class to "cell"
cell.setAttribute("class", "cell");
//Add the div HTML element to the stage
stage.appendChild(cell);
//Make it black if it's a "1"
if (pattern[row][column] === 1) {
cell.style.backgroundColor = "red";
} else {
cell.style.backgroundColor = "blue";
}
//Position the cell in the correct place
//with 10 pixels of space around it
cell.style.top = row * (SIZE + SPACE) + "px";
cell.style.left = column * (SIZE + SPACE) + "px";
cell.addEventListener('click', function() {
this.style.backgroundColor = this.style.backgroundColor == 'red' ? 'blue' : 'red';
});
}
}
#stage {
position: relative;
}
.cell {
position: absolute;
width: 30px;
height: 30px;
border: 1px solid black;
}
<div id="stage"></div>