如何访问我在 HTML 中创建的 DIV 网格
2020-04-08
795
我被困了很久,因为我无法通过行和列访问 DIV 网格。我以为我可以像 gridContainer[row][col] 那样访问它们并为其设置一些属性。控制台中的错误显示“Uncaught TypeError:无法读取 HomeScript.js:25 中未定义的属性‘0’”。附上下面的代码片段供您参考。任何建议都将不胜感激。
function genDivs (rows, cols) {
var e = document.getElementById("gridContainer");
for (var r = 0; r < rows; r++) {
var row = document.createElement("div");
row.className = "row";
for (var c = 0; c < cols; c++) {
var cell = document.createElement("div");
if (r == 10 && c == 20)
cell.className = "gridsquare begin";
else if (r == 10 && c == 40)
cell.className = "gridsquare end";
else
cell.className = "gridsquare";
row.appendChild(cell);
}
e.appendChild(row);
}
}
var gridContainer = document.getElementById("gridContainer");
// gridContainer[0][0].style.backgroundColor = "pink"; (want something like this)
var gridCols = 60;
var gridRows = Math.floor(screen.height / 25) - 2;
gridContainer.style.left = ((screen.width - 25 * gridCols) / screen.width) * 50 + "%";
console.log(((screen.width - 25 * gridCols) / screen.width) * 50);
genDivs(20, 20);
<!DOCTYPE html>
<html>
<head>
<style>
#gridContainer {
outline: 1px solid rgb(175, 216, 248);
font-size: 0;
position: absolute;
}
.row {}
.gridsquare {
width: 25px;
height: 25px;
box-shadow: 0 1px 0 rgb(175, 216, 248) inset, 1px 0px 0px rgb(175, 216, 248) inset;
display: inline-block;
}
.begin {
background-color: purple;
}
.end {
background-color: magenta;
}
</style>
</head>
<body>
<div id="gridContainer"></div>
<script type="text/javascript" src="HomeScript.js"></script>
</body>
</html>
2个回答
您可以使用 JS querySelector, 如果您想访问第一行中的 3 个 div,请使用以下语法
let square = document.querySelector(".row:nth-child(1) .gridsquare:nth-child(3)");
square.style.background = '#000';
Karthick
2020-04-08
您尝试将网格容器作为 JS 对象进行访问,但事实并非如此,您可以执行以下操作
const getRow = grid => index => {
if (grid) {
return grid.querySelector(`div.row:nth-child(${index + 1})`);
}
// handle your exception here
};
const getColumn = grid => (rowIndex, cellIndex) => {
const row = getRow(grid)(rowIndex);
if (row) {
return row.querySelector(`div:nth-child(${cellIndex + 1})`);
}
// Handle your exception here.
};
getColumn(gridContainer)(0, 0).style.backgroundColor = 'pink';
Raheel Riaz
2020-04-08