首页 > 解决方案 > 使用 javascript 动态设置网格列和行

问题描述

我需要像这样构建一个网格布局:

一个 C F
b d G
e H

这些网格项将从以下数组生成:

const options: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

现在我有以下片段

let gridColumnStart = 2;

const optionItems = options.map((option, idx) => {

    if (idx > 1 && idx % 4 === 1) {
      gridColumnStart++;
    }

    return (
     <div style={
          idx > 1
            ? { gridColumn: gridColumnStart, gridRow:  }
            : undefined
        }
     >{option}</div>
    )
});

<div style={display:grid}>{optionItems}</div>

到目前为止,我得到了正确的列,但我似乎无法弄清楚行......
索引为 2,3,4 的项目应该有 1,2,3 的 gridRowValues
再次索引为 5,6,7 的项目应该有gridRowValues of 1,2,3
应用的样式应该是这样的:

<div> a </div>
<div> b </div>
<div style={ gridRow: 1, gridColumn: 2}> c </div>
<div style={ gridRow: 2, gridColumn: 2}> d </div>
<div style={ gridRow: 3, gridColumn: 2}> e </div>
<div style={ gridRow: 1, gridColumn: 3}> f </div>
<div style={ gridRow: 2, gridColumn: 3}> g </div>
<div style={ gridRow: 3, gridColumn: 3}> h </div>

有什么建议吗?谢谢!

标签: javascriptecmascript-6

解决方案


您可以仅通过当前单元格的索引来计算网格行/列:

const gridRow = ((idx - gridColStart) % gridCols) + 1;
const gridColumn = Math.floor((idx - gridColStart) / gridCols) + gridColStart;

你可以将下面的代码改编成你的 React 组件。

const options = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const grid = document.querySelector('.my-grid');
const gridColStart = 2;
const gridCols = 3;

options.forEach((option, idx) => {
  const cell = document.createElement('div');
  const gridRow = ((idx - gridColStart) % gridCols) + 1;
  const gridColumn = Math.floor((idx - gridColStart) / gridCols) + gridColStart;
  
  cell.classList.add('cell');
  
  if (idx > gridColStart - 1) {
    if (gridRow) { cell.style.gridRow = gridRow; }
    if (gridColumn) { cell.style.gridColumn = gridColumn; }
  }
  
  if (gridRow === 1 || gridRow === -1) {
    cell.classList.add('cell-header');
  }
  
  cell.textContent = option;

  grid.appendChild(cell);
});
body {
  background: #000;
  font-family: Arial;
  font-size: smaller;
}

.my-grid {
  display: grid;
  grid-gap: 1px;
  background: #222;
  border: 1px solid #AAA;
}

.cell {
  padding: 0.5em;
  color: #FFF;
  outline: 1px solid #AAA;
  box-sizing: content-box;
}

.cell-header {
  background: #444;
}
<div class="my-grid"></div>


推荐阅读