通过以下代码片段,我现在可以将数据添加为网格布局中的行。然而,正如你所看到的,d3首先添加了所有
cell1
,然后是所有cell2
,最后是所有cell3
div,弄乱了我的网格的顺序。
我需要更改什么才能使元素按行顺序显示,即:
<div id="grid">
<div class="cell1">1/1</div>
<div class="cell2">1/2</div>
<div class="cell3">1/3</div>
<div class="cell1">2/1</div>
<div class="cell2">2/2</div>
<div class="cell3">2/3</div>
</div>
function update(data) {
d3.select('#grid')
.selectAll('.cell1')
.data(data, (d) => d.id)
.join((enter) => {
enter.append('div')
.classed('cell1', true)
.text((d) => d.cell1);
enter.append('div')
.classed('cell2', true)
.text((d) => d.cell2)
enter.append('div')
.classed('cell3', true)
.text((d) => d.cell3);
})
}
function addRow() {
const n = data.length + 1;
const newRow = {cell1: n + '/1', cell2: n + '/2', cell3: n + '/3', id: n};
data.push(newRow);
update(data);
}
const data = [
{cell1: '1/1', cell2: '1/2', cell3: '1/3', id: 1},
{cell1: '2/1', cell2: '2/2', cell3: '2/3', id: 2}
];
update(data)
#grid {
display: inline-grid;
grid-template-columns: repeat(3, 200px);
}
#grid > div:nth-of-type(3n+2) {
background-color: orange;
}
#grid > div:nth-of-type(3n+1) {
background-color: purple;
}
#grid > div:nth-of-type(3n+0) {
background-color: forestgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<div id="grid">
</div>
<button id="add" onclick="addRow()">Add Row</button>
使用类设置网格中的列。
并将自动流设置为密集
#grid {
display: inline-grid;
grid-template-columns: repeat(3, 200px);
grid-auto-flow: dense;
}
.cell1 {
background-color: orange;
grid-column: 1;
}
.cell2 {
background-color: purple;
grid-column: 2;
}
.cell3 {
background-color: forestgreen;
grid-column: 3;
}
<div id="grid">
<div class="cell1">1/1</div>
<div class="cell1">2/1</div>
<div class="cell2">1/2</div>
<div class="cell2">2/2</div>
<div class="cell3">1/3</div>
<div class="cell3">2/3</div>
</div>