如何使用JavaScript获取元素的网格坐标?

问题描述 投票:4回答:1

假设我有一个3列CSS-Grid。有没有办法,使用JavaScript,获得自动放置元素的grid-rowgrid-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-Grid中的行和列号感兴趣。

javascript jquery css css3 css-grid
1个回答
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 } ;
}
© www.soinside.com 2019 - 2024. All rights reserved.