我正在嘗試創建一個 3x3 的拼圖,div 塊網格,每次頁面重繪 時,js 都會創建 1-9 的亂數字順序陣列,并使用它們來創建“塊”,并為它們提供相應的 id并將它們附加到容器但我遇到了問題,因為并非所有塊都顯示出來。一些塊(恰好是 2 個塊)仍處于默認的“絕對”位置 (0, 0),而其余塊則正常。
請任何人都可以幫助找出問題所在?
#randomOrder 是一個 1-9 隨機排序的陣列
# CSS 片段:
.container{
width: 300px;
padding: 3px;
display: flex;
aspect-ratio: 1;
flex-wrap: wrap;
position: relative;
margin: 100px auto;
background: #777;
border-radius: 10px;
box-shadow: 0 0 0 5px #000;
}
.block{
width: 31%;
height: 31%;
margin: 1.5px;
display: flex;
font-size: 3rem;
cursor: pointer;
user-select: none;
background: #eee;
position: absolute;
border-radius: 10px;
align-items: center;
justify-content: center;
border: 2px solid #000;
box-shadow: 0 0 20px #555 inset;
}
# JS 片段:
let r = 1, c = 1
let x = 4, y = 4
randomOrder.forEach(el => {
block = document.createElement('div')
block.classList.add('block')
block.id = "b" el
if(r <= 3){
if(c <= 3){
block.style.left = x 'px'
block.style.top = y 'px'
c
x = 98
}
else{
c = 1
x = 4
y = 98
r
}
}
if (el == 9) {
block.innerText = ""
}
else {
block.innerText = el
}
container.appendChild(block)
})
這就是我在下面得到的:

但這就是我所期待的:(但以任何隨機順序)

uj5u.com熱心網友回復:
您的邏輯中有這些問題:
內部
if條件應該是if (c < 3)而不是if (c <= 3),因為在該塊c中仍然會增加ifstyle.left對and的賦值也style.top應該在執行進入塊時發生,所以這else兩個賦值應該在ifblock應該用varorletorconst關鍵字宣告。現在它被隱式定義為全域變數,這是不好的做法,并且在嚴格模式下運行時不允許。
不是問題,但if (r <= 3)確實沒有必要——情況總是如此。
考慮到這些注釋,相關代碼變為:
const block = document.createElement('div')
block.classList.add('block')
block.id = "b" el
block.style.left = x 'px'
block.style.top = y 'px'
if(c < 3){
c
x = 98
}
else{
c = 1
x = 4
y = 98
r
}
然而,有一種更簡單的方法來確定xand y,使用余數運算子 ( ) 和可以在回呼%中作為引數獲取的索引。forEach
不相關,但if..else可以使用條件運算子 ( ? :) 縮短結尾:
const container = document.querySelector(".container");
const randomOrder = [1, 2, 3, 4, 5, 6, 7, 8, 9];
randomOrder.forEach((el, i) => {
const block = document.createElement('div');
block.classList.add('block');
block.id = "b" el;
block.style.left = (4 98*(i % 3)) 'px'
block.style.top = (4 98*Math.floor(i / 3)) 'px'
block.innerText = el == 9 ? "" : el;
container.appendChild(block);
});
.container{
width: 300px;
padding: 3px;
display: flex;
aspect-ratio: 1;
flex-wrap: wrap;
position: relative;
margin: 100px auto;
background: #777;
border-radius: 10px;
box-shadow: 0 0 0 5px #000;
}
.block{
width: 31%;
height: 31%;
margin: 1.5px;
display: flex;
font-size: 3rem;
cursor: pointer;
user-select: none;
background: #eee;
position: absolute;
border-radius: 10px;
align-items: center;
justify-content: center;
border: 2px solid #000;
box-shadow: 0 0 20px #555 inset;
}
<div class="container"></div>
以下是index 的所有可能值的%and運算式的計算結果:Math.floori
指數i |
i % 3 |
Math.floor(i / 3) |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 0 | 1 |
| 4 | 1 | 1 |
| 5 | 2 | 1 |
| 6 | 0 | 2 |
| 7 | 1 | 2 |
| 8 | 2 | 2 |
所以你可以看到它i % 3代表一個列索引和Math.floor(i / 3)一個行索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/523688.html
