如何找到 e.target 的下一个(或多个)元素?
网格 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。 如果船舶是承运人,则当前格加上下四个格。
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。我已经尝试过closest(),但这在这种特殊情况下不起作用。
我想做的是使用拖放掉落以将船只放置在我的网格中。因此,如果用户拖动“驱逐舰”或“潜艇”,我希望能够获取当前的 e.target 和下一个 div。如果用户拖动“Carrier”,我希望能够获取当前的 e.target 和接下来的四个 div,因为载体的大小为 5。
The grids div sample.
<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>
So if the grid with the 1 is being hovered over, I want to target the one with 2,3,4 and upto 5 at maximum.
If the user is dragging the ships destroyer/submarine, I want to target the
current div and the next div.
if ship is cruiser, current div plus next two div.
if ship is battleship, current div plus next three div.
if ship is carrier, current div plus next four div.
const grids = document.querySelectorAll('.grid');
grids.forEach(el => {
el.addEventListener('dragenter', (e) => {
// Find the next few dom elements that comes after e.target
});
});
The grids here represent a 10*10 grid in the dom which are just divs.
When I hover over certain divs, I want to be able to get the next few divs that comes after the current div. I have tried closest() but that does not work in this particular situation.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用索引并获取数组中的下一个元素
或者你可以使用 DOM 方法
You can use the index and get the next elements in the array
Or you can use DOM methods
使用了 nextSiblingElement
Used nextSiblingElement