網格 div 示例。
<div class="gameBoard">
<div class="grid">1</div>
<div class="grid">2</div>
<div class="grid">3</div>
<div class="grid">4</div>
<div class="grid">5</div>
<div class="grid">6</div>
<div class="grid">7</div>
<div class="grid">8</div>
<div class="grid">9</div>
<div class="grid">10</div>
</div>
因此,如果將帶有 1 的網格懸停在上方,我想以 2、3、4 和最多 5 為目標。
如果用戶正在拖動驅逐艦/潛艇,我想定位當前 div 和下一個 div。
如果船是巡洋艦,則當前 div 加上接下來的兩個 div。如果船是戰艦,則當前 div 加上接下來的三個 div。如果船是承運人,則當前 div 加上接下來的四個 div。
const grids = document.querySelectorAll('.grid');
grids.forEach(el => {
el.addEventListener('dragenter', (e) => {
// Find the next few dom elements that comes after e.target
});
});
這里的網格代表 dom 中的 10*10 網格,它們只是 div。當我將滑鼠懸停在某些 div 上時,我希望能夠獲得當前 div 之后的下幾個 div。我試過最接近(),但在這種特殊情況下不起作用。
What I'm trying to do is to use drag & drop to place ships in my grid. So if the user is dragging the "destroyer" or the "submarine", I want to be able to get the current e.target and the next divs. If the user is dragging the "Carrier", I want to be able to get the current e.target and the next four divs cuz the size of the carrier is 5.
uj5u.com熱心網友回復:
您可以使用索引并獲取陣列中的下一個元素
const cells = Array.from(document.querySelectorAll('.cell'));
cells.forEach((el, index) => {
el.addEventListener('click', (evt) => {
const nextSiblings = cells.slice(index 1);
console.log(nextSiblings);
});
});
.cell {
display: inline-block;
width: 25px;
height: 25px;
border: 1px solid black;
}
<div class="my-grid">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
或者你可以使用 DOM 方法
const grid = document.querySelector(".grid");
grid.addEventListener("click", e => {
let cell = e.target.closest(".cell");
if (!cell) return;
const siblings = [];
while (cell = cell.nextElementSibling) {
siblings.push(cell);
}
console.log(siblings);
});
.cell {
display: inline-block;
width: 25px;
height: 25px;
border: 1px solid black;
}
<div class="grid">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
uj5u.com熱心網友回復:
使用 nextSiblingElement
grids.forEach(el => {
el.addEventListener('dragenter', (e) => {
//if (currentShipLength === 2) {
const one = e.target;
const two = e.target.nextElementSibling;
const three = two.nextElementSibling;
const four = three.nextElementSibling;
const five = four.nextElementSibling;
console.log(one, two, three, four, five);
//};
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452224.html
標籤:javascript html css dom dom-events
