HTML
<div class="row">
<div class="col">first</div>
<div class="col">second</div>
<div class="col">third</div>
</div>
SCSS
$statistics: ("first", "second", "third");
:root {
--first: red;
--second: blue;
--third: green;
}
.row {
@for $i from 1 through length($statistics) {
@each $variable in $statistics {
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
}
我想像这样编译它
.row {
.col:nth-child(1) {
color: var(--first);
}
.col:nth-child(2) {
color: var(--second);
}
.col:nth-child(3) {
color: var(--third);
}
}
我哪里错了?每个 .col 都有全部 3 种颜色。我希望每个统计数据在 $statistics 中只有一种颜色。第一个.col有第一个,第二个.col有第二个,依此类推...
编辑 如果像这样定义变量会怎样?
$statistics: (
"header": ("first", "second", "third")
);
最佳答案
问题是您有一个第一个循环,其中 @for
循环遍历 $statistics
的所有值,然后 @each
执行相同的操作这会导致重复值。这应该通过单个循环来完成。我可以想到两种方法来实现你想要的:
.row {
@for $i from 1 through length($statistics) {
$variable: nth($statistics, $i);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
或
.row {
@each $variable in $statistics {
$i: index($statistics, $variable);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
}
如果变量定义为:
$statistics: (
"header": ("first", "second", "third")
);
您可以使用map-get
来获取变量。像这样的东西:
$header: map-get($statistics, "header");
@each $variable in $header {
$i: index($header, $variable);
.col:nth-child(#{$i}) {
color: var(--#{$variable});
}
}
这与之前相同,但使用 $header
而不是 $statistics
循环
关于html - SCSS : How to combine @for with @each?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447880/