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

fwzugrvs  于 2023-06-05  发布在  jQuery
关注(0)|答案(3)|浏览(440)

假设我有一个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中的行和列编号感兴趣。

j13ufse2

j13ufse21#

上面的答案是一个很好的开始,并使用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,它在日历上以指定的偏移量显示了它的运行情况。

v1l68za4

v1l68za42#

//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 } ;
}
lc8prwob

lc8prwob3#

这里另一个解决方案考虑到列跨度

function getGridPosition(elem) {
    var gridContainer = elem.parent();
    var simpleEl = elem.get(0);
    var gridItems = gridContainer.children('div');
    const colCount = $(gridContainer).css('grid-template-columns').split(' ').length;

    var row = 0;
    var col = 0;

    gridItems.each(function(index,el) {

        var item = $(el);
        if(simpleEl==el) {
            //console.log("FOUND!")
            return false;
        }
        var gridCols  = item.css("grid-column");
        if(gridCols != undefined && gridCols.indexOf("span")>=0){
            var gridColumnParts = gridCols.split('/');
            var spanValue = parseInt(gridColumnParts[0].trim().split(' ')[1], 10);
            //console.log("spanValue: " + spanValue);
            col = col+spanValue;
        }else{
            col++;
        }
        if(col>=colCount){
            col=0;
            row++;
        }
    });

    return {
        row: row,
        col: col
    };
}

相关问题