javascript - 使用 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>
有什么建议吗?谢谢!
解决方案
您可以仅通过当前单元格的索引来计算网格行/列:
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>
推荐阅读
- c - 使用 c 将多个值从一个文件中定义的函数传递到另一个文件
- java - Maven 上的项目未导入其依赖项
- javascript - Javascript 捕获 console.trace() 而不是将其写入控制台
- c# - 我错过了数据库的这些错误
- docker - 无法在 Docker 容器中检索最新版本的 Debian 软件包
- python - 在融合的 Kafka 中更改模式名称策略
- visual-studio - Visual Studio 是否有一个选项,以便 Resume Suspended Work 不会删除搁置集?
- python - How to cut non-alphanumeric prefix and suffix from a string in Python?
- plot - 如何在ps文件的ghostscript图中旋转方向?
- java - 如何比较两个 MimeMessage.java 对象以确保它们相同?