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 都具有三种颜色。我希望每个统计信息在$ statistics中仅具有一种颜色。第一个 .col 具有第一个,第二个 .col 具有第二个,等等...
编辑 如果变量是这样定义的呢?
$statistics: (
"header": ("first", "second", "third")
);
答案 0 :(得分:2)
问题是,您有一个第一个循环,其中@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
循环