抱歉,帖子有點長,只是為了非常清楚我需要什么。我正在制作一個 8x8 的電路板。我喜歡使用回圈。作業完美。
// Create a center tag to center all the elements
var center = document.createElement('center');
var count = 1;
// Create a table element
var ChessTable = document.createElement('table');
for (var i = 0; i < 8; i ) {
// Create a row
var tr = document.createElement('tr');
for (var j = 0; j < 8; j ) {
// Create a cell
var td = document.createElement('td');
// If the sum of cell coordinates is even
// then color the cell white
if ((i j) % 2 == 0) {
// Create a class attribute for all white cells
td.setAttribute('class', 'cell whitecell');
tr.appendChild(td);
// td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
}
// If the sum of cell coordinates is odd then
// color the cell black
else {
// Create a class attribute for all black cells
td.setAttribute('class', 'cell blackcell');
// Append the cell to its row
tr.appendChild(td);
// td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
}
}
// Append the row
ChessTable.appendChild(tr);
}
center.appendChild(ChessTable);
// Modifying table attribute properties
ChessTable.setAttribute('cellspacing', '0');
ChessTable.setAttribute('width', '270px');
document.body.appendChild(center);
console.log(ChessTable);
現在我需要做出選擇,如果您單擊某個單元格,單元格會改變顏色。也很完美。
function respondToClick(event)
{
if (event.target.nodeName.toLowerCase() === 'td') {
event.target.style.backgroundColor = "green";
}
} ChessTable.addEventListener("click", respondToClick);
知道我需要隨機單元格然后著色。我做到了并且效果很好,我使用了 0-63 的隨機函式,然后將數字轉換為基數 8,因為我想將每個單元格與行和列進行比較,然后拆分數字以了解每一行和每一列.
function getRandomArbitrary(min, max)
{
return Math.round(Math.random() * (max - min) min);
}
//random numbers
var a = [];
for (var j = 0; j < 5; j ) {
a[j] = getRandomArbitrary(0, 64)
}
console.log(a)
var b = [];
b = a;
//convert to base 8
for (var j = 0; j < 5; j ) {
b[j]=b[j].toString(8);
}
console.log(b);
const cells = []
//seperate the digidt for board
for (var j = 0; j < 5; j )
{
b[j] = b[j].toString(8);
var digits = b[j].toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);
// coloring the random numbers
if (realDigits[1] != null) {
cells[j] = ChessTable.rows[realDigits[0]].cells[realDigits[1]];
cells[j].style.backgroundColor = "yellow";
}
else {
cells[j] = ChessTable.rows[0].cells[realDigits[0]];
cells[j].style.backgroundColor = "yellow";
}
}
這也很好用。
現在我遇到的最后一個問題是我需要這樣做。首先計算機需要隨機選擇單元格,但還不需要顯示它們,當滑鼠點擊時,用戶需要知道點擊的是計算機隨機選擇的單元格。
所以我在respondToClick函式中添加了這個。
function respondToClick(event, cells)
{
if (event.target.nodeName.toLowerCase() === 'td')
{
event.target.style.backgroundColor = "green";
if (event.target.nodeName.toLowerCase() == cells[0]) {
alert("correct")
}
}
}
在單元格中,我有“單元格的位置(我添加了一張照片)(單元格 [0] 僅用于測驗,我可以在每次單擊時使用回圈來遍歷所有單元格)
因此,當我將事件與單元格 [0] 進行比較時,出現錯誤。我在這里缺少什么?
uj5u.com熱心網友回復:
首先,讓我們更好地組織您的代碼,以便更輕松地使用電路板。
您目前正在使用桌子制作電路板,我不推薦這樣做。相反,最好使用<div>.
此外,您使用的是不需要的二維陣列,有時會使代碼過于復雜。
我建議改用一維陣列。
function makeBoard(height, width, init_callback){
return Array(height*width).fill(0).map(init_callback);
}
Make board 將創建一個長高 * 寬的陣列,并使用回呼函式填充它。
回呼看起來像這樣:
function initCell(){
const cell = document.createElement("div");
// make changes to cell
cell.classList.add("cell")
return cell
}
然后,您可以輕松地將網格添加到 HTML 中,使用.append().
// <div id="board" />
const board = document.querySelector("#board");
const pieces = makeBoard(8, 9, initCell);
// append can take multiple elements. Making it easy to add our elements by de-structering our array.
board.append(...pieces);
現在,要設計板的樣式,我們不需要使用 JavaScript。CSS 非常強大,可以輕松為我們處理。
.cell {
height: 40px;
width: 40px;
background-color: white;
}
.cell:nth-child(odd){
background-color: brown;
}
.cell:nth-child(9n 1){
display: none;
}
#board {
height: 320px;
width: 320px;
display: grid;
grid-template-columns: repeat(8, 40px);
}
如果你看看珍貴的 JS 和 CSS,我們的網格實際上是 8x9 而不是 8x8。這是因為,為了輕松創建棋盤圖案,我們正在創建一個 8x9 棋盤,然后移除每行的第 9 個單元格,以創建棋盤。
現在添加點擊事件,相對容易一些。
document.querySelectorAll(".cell").forEach(cell => {
cell.addEventListener("click", cellClickHandler)
});
該代碼會將onClick單元格上的事件設定為cellClickHandler函式。
要更改 bg 顏色,單擊時,它將如下所示:
function cellClickHandler(e){
e.target.classList.toggle("green")
}
現在這是一個可運行的版本,看看我們到目前為止有什么:
function makeBoard(height, width, init_callback){
return Array(height*width).fill(0).map(init_callback)
}
function initCell(){
const cell = document.createElement("div");
// make changes to cell
cell.classList.add("cell");
return cell
}
// <div id="board" />
const board = document.querySelector("#board");
const pieces = makeBoard(8, 9, initCell);
board.append(...pieces);
document.querySelectorAll(".cell").forEach(cell => {
cell.addEventListener("click", cellClickHandler)
});
function cellClickHandler(e){
e.target.classList.toggle("green")
}
.cell {
height: 40px;
width: 40px;
background-color: white;
}
.cell:nth-child(odd){
background-color: brown;
}
.cell:nth-child(9n 1){
display: none;
border: none;
}
.green {
background-color: green !important;
}
#board {
height: 320px;
width: 320px;
display: grid;
grid-template-columns: repeat(8, 40px);
}
<div id="board" />
uj5u.com熱心網友回復:
您需要使用bind或閉包將單元格引數傳遞給處理程式。
const chessTableClickHandler = respondToClick.bind(null, cells);
ChessTable.addEventListener("click", chessTableClickHandler);
function respondToClick(cells, event)
{
if (event.target.nodeName.toLowerCase() === 'td')
{
event.target.style.backgroundColor = "green";
if (event.target.nodeName.toLowerCase() == cells[0]) {
alert("correct")
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398100.html
標籤:javascript html css
上一篇:使用CSS按鈕切換影像
