您在这里有两个任务:
- 检测元件。
- 获取元素的列/行。
检测元件
如果为每个网格项添加所需的事件处理程序,则可以避免检测元素。
但是,如果您想添加鼠标悬停(或其他事件处理程序),您可以通过每个网格项添加循环并使用element.getBoundingClientRect()
方法。演示(我将添加点击处理程序以避免污染控制台):
var grid = document.querySelector(".grid");
grid.addEventListener("click", function(event) {
var gridItems = this.children;
for (var i = 0; i < gridItems.length; i++) {
var gridItem = gridItems[i];
var rect = gridItem.getBoundingClientRect();
var elementDetected = event.clientX >= rect.left
&& event.clientX <= rect.right
&& event.clientY >= rect.top
&& event.clientY <= rect.bottom;
if (elementDetected) {
console.log(gridItem);
return;
}
}
console.log("no element detected!");
});
.grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
grid-gap: 10px;
}
/* styles just for demo */
.grid__item {
background-color: tomato;
color: white;
/* styles for centering text */
display: flex;
align-items: center;
justify-content: center;
}
<div class="grid">
<div class="grid__item">One</div>
<div class="grid__item">Two</div>
<div class="grid__item">Three</div>
<div class="grid__item">Four</div>
<div class="grid__item">Five</div>
<div class="grid__item">Six</div>
<div class="grid__item">Seven</div>
<div class="grid__item">Eight</div>
<div class="grid__item">Nine</div>
</div>
由于方法的原因,使用 jQuery 会使这项任务更加简单is(":hover")
。
$(".grid").click(function(event) {
var hoveredGridItems = $(this).children()
.filter(function() { return $(this).is(":hover"); });
if (hoveredGridItems.length > 0)
console.log(hoveredGridItems[0]);
else
console.log("no element detected!");
});
.grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
grid-gap: 10px;
}
/* styles just for demo */
.grid__item {
background-color: tomato;
color: white;
/* styles for centering text */
display: flex;
align-items: center;
justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
<div class="grid__item">One</div>
<div class="grid__item">Two</div>
<div class="grid__item">Three</div>
<div class="grid__item">Four</div>
<div class="grid__item">Five</div>
<div class="grid__item">Six</div>
<div class="grid__item">Seven</div>
<div class="grid__item">Eight</div>
<div class="grid__item">Nine</div>
</div>
获取元素的列/行
我会在这里只信任 CSS,因此只有当我们明确设置grid-column
和grid-row
属性时,获取列和行才能按预期工作。因此,您拥有适用于各种情况的代码行:
// pure JS
var styles = window.getComputedStyle(gritItem);
var gridColumn = styles["grid-column-start"];
var gridRow = styles["grid-row-start"];
// jquery
var gridColumn = $gridItem.css("grid-column");
var gridRow = $griditem.css("grid-row");
如果gridColumn
和/或gridRow
的值不是auto / auto
,那么您肯定知道行和列。
但是在自动放置时检测行和列是非常不可靠的,因为可能的列跨度/行跨度值不同,margins
网格项的可能,align-self
以及justify-self
(元素只能占据部分网格区域的情况)等。