【问题标题】:Is there a way to detect which CSS grid column and row an element is in using javascript?有没有办法使用javascript检测元素在哪个CSS网格列和行?
【发布时间】:2020-05-22 21:37:00
【问题描述】:

有没有办法在 javascript 中动态检测 CSS 网格中元素所在的网格列和行?

我有一个网格,我设置了三个断点,使其具有 4、3 或 2 列。

我想要做的是,如果用户在一个单元格中单击,动态覆盖单元格中的一个新元素,紧邻被单击的单元格的右侧,除非它位于最右边的列中,在这种情况下覆盖元素将进入左侧的单元格。

我知道我可以使用grid-columngrid-row 来指定要放入新事物的单元格,但是为了能够使用它,我需要知道该单元格的列和行被点击了。

如何动态确定?

【问题讨论】:

    标签: javascript css grid css-grid


    【解决方案1】:

    这里。将其绑定到单击,但您可以以任何您喜欢的方式访问此功能。单击块以查看它是否是最后一列。该函数接受当前的grid-template-columns,因此它可以在任何断点上工作。

    //Add click event for any child div of div = grid
    $(document).ready(function() {
      $('.grid').on('click', 'div', function(e) {  
        GetGridElementsPosition($(this).index(), $(this)); //Pass in the index of the clicked div
      });
    });
    
    function GetGridElementsPosition(index, element) {
    
      //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 colPosition = index % colCount;
      const rowPosition = Math.floor(index / colCount);
      
      /* determine if it is a last column */
      if (colPosition==(colCount-1)) {
        $(element).html('row:'+rowPosition+'. col:'+colPosition+'. Last column');
      } else {
        $(element).html('row:'+rowPosition+'. col:'+colPosition+'. Not last column');
      }
    
    }
    .grid {
      display: grid;
      grid-template-columns: repeat( 3, 1fr );
      grid-row-gap: 1em;
      grid-column-gap: 1em;
    }
    
    .grid div {
      height: 2em;
      background: blue;
      color: #fff;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="grid">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    【讨论】:

    • 有趣,这个解决方案对您有帮助吗?
    • 我最终实际上不必执行我所描述的操作,我将网格项设置为执行“卡片翻转”类型的动画,以将附加元素保持在与之前相同的网格单元中点击。但关键 $('.grid').css('grid-template-columns').split(' ').length 正是我正在寻找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2019-07-06
    • 2020-03-16
    • 2015-07-03
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多