我有这个 CSS 网格,我想以棋盘图案交替网格颜色。这是 HTML/CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<style>
body {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
background-color: #578a34
}
#game-board {
background-color: #aad751;
width: 100vmin;
height: 100vmin;
display: grid;
grid-template-rows: repeat(21, 1fr);
grid-template-columns: repeat(21, 1fr);
}
.dark-tile {
background-color: #a2d149;
}
.light-tile {
background-color: #aad751;
}
.snake {
background-color: #4e7cf6;
}
.food {
background-color: #e7471d;
}
</style>
<script src="game.js" defer type="module"></script>
</head>
<body>
<div id="game-board">
<div style="grid-row-start: 11; grid-column-start: 11;" class="snake"></div>
<div style="grid-row-start: 7; grid-column-start: 14;" class="food"></div>
</div>
</body>
</html>
然而,它在食物和蛇所在的地方变得一团糟。我怀疑这是由于
.appendChild(tile)
。这是绘制棋盘的代码:
export function draw(gameBoard) {
for (let j = 0; j < GRID_SIZE+1; j++){
for (let i = 0; i < GRID_SIZE+1; i++){
if (Math.abs(i % 2) == 1){
const tile = document.createElement('div')
tile.classList.add('dark-tile')
gameBoard.appendChild(tile)
} else {
const tile = document.createElement('div')
tile.classList.add('light-tile')
gameBoard.appendChild(tile)
}
}
}
}
任何帮助将不胜感激!