css 用JavaScript制作7x7棋盘

eagi6jfj  于 2023-02-26  发布在  Java
关注(0)|答案(2)|浏览(105)

当我运行下面的代码时,我的网页上什么也没有显示,我想知道为什么。
我不太确定我在这里做错了什么。我试着通过ChatGPT运行这个,它说它应该工作,但当我运行它的页面是完全空白的。

for (let i = 0; i < 49; i++) {
  const createDivs = document.createElement('div');
  document.body.appendChild(createDivs);
  if (i % 2 === 0) {
    createDivs.classList.add('set-to-black');
  } else {
    createDivs.classList.add('set-to-red');
  }
}

const setToBlack = document.getElementsByClassName('set-to-black');

for (let i = 0; i < setToBlack.length; i++) {
  setToBlack[i].style.backgroundColor = 'black';
  setToBlack[i].style.height = '60px';
};

const setToRed = document.getElementsByClassName('set-to-red');

for (let i = 0; i < setToRed.length; i++) {
  setToRed[i].style.backgroundColor = 'red';
   setToRed[i].style.height = '60px';
};
enyaitl3

enyaitl31#

取消代码注解,删除设置高度的行,然后添加一点CSS就可以了。下面是完整注解的示例。

for (let i = 0; i < 49; i++) {
  const createDivs = document.createElement('div');
  document.body.appendChild(createDivs);
  if (i % 2 === 0) {
    createDivs.classList.add('set-to-black');
  } else {
    createDivs.classList.add('set-to-red');
  }
}

const setToBlack = document.getElementsByClassName('set-to-black');
for (let i = 0; i < setToBlack.length; i++) {
  setToBlack[i].style.backgroundColor = 'black';
  /*setToBlack[i].style.height = '60px'; removed this so the divs are square */
};

const setToRed = document.getElementsByClassName('set-to-red');
for (let i = 0; i < setToRed.length; i++) {
  setToRed[i].style.backgroundColor = 'red';
   /*setToRed[i].style.height = '60px'; removed this so the divs are square*/
};
div {
  width: calc(100% / 7); /* make each div 1/7th of the overall width so the 8th, 16th, etc start on a new linw */
  display: inline-block; /* make them behave like inline block elements so siblings elements sit next to each other */
  vertical-align: top; /* this removes the space for descenders */
  aspect-ratio: 1 / 1; /* make them all square */
}
cqoc49vn

cqoc49vn2#

使用CSS Grid,您可以通过一个循环来解决这个问题。
1.设置容器。
1.使用CSS Grid创建一些CSS,并使用nth-child来标识哪个方块应该是黑色/红色。
1.创建一些HTML,用square类标识每个正方形,并根据迭代索引是奇数还是偶数添加一个颜色类。
1.最后将HTML添加到容器元素中。

const container = document.querySelector('.container');
const html = [];

for (let i = 0; i < 49; i++) {
  const color = i % 2 === 0 ? 'red' : 'black';
  html.push(`<div class="square ${color}"></div>`);
}

container.innerHTML = html.join('');
.container { display: grid; grid-template-columns: repeat(7, calc(100% / 7)); width: 100%; }
.square { calc(100% / 7); aspect-ratio: 1 / 1;}
.square:nth-child(odd) { background-color: black; }
.square:nth-child(even) { background-color: red; }
<section class="container"></section>

其他文件

相关问题