我有一个用JavaScript创建的简单棋盘,我想在棋盘的侧面添加字母和数字,以便看起来像真正的棋盘。我尝试使用for循环添加带有字母和数字的元素,但条件似乎是错误的,因为它不起作用。这是我的HTML代码:
let table = document.createElement("table");
for (let i = 8; i > 0; i--) {
let tr = document.createElement('tr');
let number = document.createElement('td');
number.className = 'number';
number.innerHTML = i;
tr.appendChild(number);
for (let j = 0; j < 8; j++) {
let td = document.createElement('td');
if (i % 2 == j % 2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
* {
margin: 0;
padding: 0;
}
table {
border-spacing: 0;
margin: 20px 20px;
}
.black {
width: 38px;
height: 38px;
background: black;
border: 1px solid transparent;
}
.white {
width: 38px;
height: 38px;
background: white;
border: 1px solid black;
}
.number {
padding-right: 10px;
font-size: 18px;
font-weight: bold;
}
答案 0 :(得分:2)
这就是我要做的(仍然需要对样式进行一些调整):
let table = document.createElement("table");
let letters = "ABCDEFGH";
for (let i = 0; i < 9; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < 9; j++) {
let td = document.createElement('td');
if (j === 0) {
td.textContent = 8-i || '';
tr.appendChild(td);
continue;
}
if (i === 8) {
td.textContent = letters.charAt(j-1);
td.classList.add('letter');
tr.appendChild(td);
continue;
}
if (i % 2 == j % 2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
* {
margin: 0;
padding: 0;
}
table {
border-spacing: 0;
border: 0;
margin: 20px 20px;
}
tr:not(:last-child) td:not(:first-child) {
border: 1px solid black;
}
.black {
width: 40px;
height: 40px;
background: black;
}
.white {
width: 40px;
height: 40px;
background: white;
}
.letter {
text-align: center;
}
答案 1 :(得分:1)
使用CSS step5()
伪元素和String.fromCharCode()
:before
let table = document.createElement("table");
for (let i = 0; i < 8; i++) {
let tr = document.createElement('tr');
tr.setAttribute('data-row', 8 - i);
for (let j = 0; j < 8; j++) {
let td = document.createElement('td');
if (i == 7) {
td.setAttribute('data-col', String.fromCharCode(65 + j));
}
if (i % 2 == j % 2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);