我想遍历所有 <td>
我的表的元素将每个元素与我在名为 $options-colours 的 sass 映射中设置的颜色相匹配。此刻我被绊倒了,因为只有前 3 种颜色因为新的 <tr>
而不断重复。每一次。我知道我需要增加 <tr>
nth-of-type
或 nth-child
每次我的索引都可以被 3 整除但我不确定如何将它们拼凑在一起时,有人可以解释我如何才能做到这一点吗?
SCSS
table {
width: 100%;
tr {
@for $i from 1 through length($option-colours) {
/*
&:nth-child(#{$i}) {
if $i % 3 == 0 increment?
}
*/
td {
width: 33.3333%;
height: 100px;
&:nth-of-type(#{$i}) {
background: nth($option-colours, $i);
}
}
}
}
}
代码笔: http://codepen.io/styler/pen/oCKfJ?editors=110
HTML
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
最佳答案
基本上,我创建了一些变量来跟踪我们应该为哪一行以及哪个单元格设置样式。在循环的三次迭代之后,单元格计数器重置为 1,行计数器递增。我不太确定组织像这样的大型 SASS 循环的最佳实践是什么,所以欢迎任何反馈。
http://codepen.io/sdsanders/pen/nchtb?editors=110
table {
width: 100%;
$row: 1;
$cell: 1;
tr {
@for $i from 1 through length($option-colours) {
&:nth-child(#{$row}) {
td {
&:nth-child(#{$cell}) {
background: nth($option-colours, $i);
}
$cell: $cell + 1;
@if $cell == 4 {
$cell: 1;
$row: $row +1;
}
}
}
}
td {
width: 33.3333%;
height: 100px;
}
}
}
相关的 CSS 输出如下所示:
table tr:nth-child(1) td:nth-child(1) {
background: #fcfcfc;
}
table tr:nth-child(1) td:nth-child(2) {
background: #ebebea;
}
table tr:nth-child(1) td:nth-child(3) {
background: #d7d7d6;
}
table tr:nth-child(2) td:nth-child(1) {
background: #c2c2c1;
}
...
关于html - 如何循环遍历表中的所有 td 元素,添加与 sass 颜色映射不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24614132/