You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript统计动态Grid网格布局每一行的列数

完全可以统计,哪怕行数动态变化、存在跨列场景也能实现,核心逻辑是通过子元素的顶部偏移量区分行归属:
同一行的Grid子元素在页面上的顶部偏移量(offsetTop)完全一致,我们可以以此为依据对所有子元素分组;每组的元素个数就是当前行的子元素列数,如果需要统计实际占用的网格列槽数,额外读取每个元素的gridColumn属性计算跨列值累加即可;行数变化后重新执行一次统计逻辑就能拿到最新的行列数据。

完整实现代码

HTML

<div class="grid">
  <div class="column">1</div>
  <div class="column">2</div>
  <div class="column">3</div>
  <div class="column">4</div>
</div>

<br />

Row 2
<div class="grid">
  <div class="column">1</div>
  <div class="column">2</div>
</div>
<br />

<div class="result">
  <p>Row 1:</p>
  <small>Columns:</small><br />
</div>
<div class="result">
  <p>Row 2:</p>
  <small>Columns:</small><br />
</div>

CSS

.grid {
  display: grid;
  grid-template-columns: auto auto auto;
  justify-items: start;
  grid-gap: 10px;
}

.grid div {
  border: 1px solid #000;
  width: 100%;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
}

.result {
  border: 1px solid black;
  margin: 10px 0;
}

button {
  margin: 40px 0;
}

p {
  color: green;
}

JavaScript

// 统计所有grid容器的行列数据
function calcGridRows() {
  const allGrids = document.querySelectorAll('.grid');
  const resultContainers = document.querySelectorAll('.result');
  
  allGrids.forEach((grid, gridIndex) => {
    const items = grid.querySelectorAll('.column');
    const rowGroups = {};
    
    // 按顶部偏移量分组,相同值属于同一行
    items.forEach(item => {
      // 如果Grid容器有CSS transform偏移,替换为 item.getBoundingClientRect().top 即可
      const top = item.offsetTop;
      if (!rowGroups[top]) rowGroups[top] = [];
      rowGroups[top].push(item);
    });
    
    // 转成行数组,按y轴坐标排序避免顺序错乱
    const rows = Object.values(rowGroups).sort((a, b) => a[0].offsetTop - b[0].offsetTop);
    
    // 输出到对应结果容器
    const result = resultContainers[gridIndex];
    const smallEl = result.querySelector('small');
    // 统计行内子元素个数
    smallEl.textContent = `Columns: ${rows.map(row => row.length).join('、')}`;

    // 如需统计含跨列的实际列槽占用数,替换上面的赋值逻辑为以下代码
    // const colCounts = rows.map(row => {
    //   return row.reduce((total, item) => {
    //     const span = +getComputedStyle(item).gridColumnEnd.split(' ')[1] || 1;
    //     return total + span;
    //   }, 0)
    // })
    // smallEl.textContent = `Columns(含跨列): ${colCounts.join('、')}`;
  })
}

// 页面加载完成后执行统计
window.addEventListener('load', calcGridRows);
// 如果有动态增删行列、窗口大小变化等会触发Grid布局变动的操作,触发后重新调用calcGridRows即可

如果你的Grid存在动态增删子元素、窗口大小变化导致换行的场景,只需要在对应的触发时机(比如元素增删回调、resize防抖回调)重新调用calcGridRows方法就能拿到最新的行列统计数据。

内容的提问来源于stack exchange,提问作者zana10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:03