假设我有一个3列CSS-Grid。有没有一种使用JavaScript的方法来获取自动放置的元素的grid-row
和grid-column
?
示例:
console.log($('#test').css('grid-row'), $('#test').css('grid-column'));
// expected output: 2 3
// actual output: two empty strings
.grid {
display: grid;
grid-template-columns: repeat( 3, 1fr);
}
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="test"></div>
<div></div>
<div></div>
<div></div>
</div>
以下是示例的JSFiddle:https://jsfiddle.net/w4u87d2f/7/
在此示例中,我可以通过对元素进行计数并知道网格具有三列来找出答案:
grid-column = $('#test').index() % 3 + 1;
grid-row = Math.ceil( $('#test').index() / 3 )
但这仅适用于非常简单的网格,并且还意味着我必须考虑更改列数的断点。
编辑:这不是Retrieve the position (X,Y) of an HTML element的副本,因为我对像素坐标不感兴趣,但对CSS网格中的行号和列号不感兴趣。
答案 0 :(得分:2)
//Add click event for any child div of div = grid
$(document).ready(function(){
$('.grid').on('click', 'div', function(e){
GetGridElementsPosition($(this).index()); //Pass in the index of the clicked div
//Relevant to its siblings, in other words if this is the 5th div in the div = grid
});
});
function GetGridElementsPosition(index){
//Get the css attribute grid-template-columns from the css of class grid
//split on whitespace and get the length, this will give you how many columns
const colCount = $('.grid').css('grid-template-columns').split(' ').length;
const rowPosition = Math.floor(index / colCount);
const colPosition = index % colCount;
//Return an object with properties row and column
return { row: rowPosition, column: colPosition } ;
}
答案 1 :(得分:1)
以上答案是一个很好的开始,它使用jQuery。这是一个纯Javascript等效项,并且如果您指定了第一个子元素的网格列(例如,在您指定一个月的第一天的日历中),也会实现一个“偏移”
function getGridElementsPosition(index) {
const gridEl = document.getElementById("grid");
// our indexes are zero-based but gridColumns are 1-based, so subtract 1
let offset = Number(window.getComputedStyle(gridEl.children[0]).gridColumnStart) - 1;
// if we haven't specified the first child's grid column, then there is no offset
if (isNaN(offset)) {
offset = 0;
}
const colCount = window.getComputedStyle(gridEl).gridTemplateColumns.split(" ").length;
const rowPosition = Math.floor((index + offset) / colCount);
const colPosition = (index + offset) % colCount;
//Return an object with properties row and column
return { row: rowPosition, column: colPosition };
}
function getNodeIndex(elm) {
var c = elm.parentNode.children,
i = 0;
for (; i < c.length; i++) if (c[i] == elm) return i;
}
function addClickEventsToGridItems() {
let gridItems = document.getElementsByClassName("grid-item");
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].onclick = (e) => {
let position = getGridElementsPosition(getNodeIndex(e.target));
console.log(`Node position is row ${position.row}, column ${position.column}`);
};
}
}
addClickEventsToGridItems();
这是corresponding Pen,可在指定偏移量的日历上显示它的运行情况。