我有一个相同的类列表,但需要在它们内部有不同的背景引用:
.name-one {
@include thumb-source;
background: url('../name-one.png') no-repeat;
}
.name-two {
@include thumb-source;
background: url('../name-two.png') no-repeat;
}
.name-three {
@include thumb-source;
background: url('../name-three.png') no-repeat;
}
and it goes on for a while ...
可以看到,类名也复制了文件名。我想知道是否有一种方法来编写一个函数使用scss传递一个数组与我的类名在其中,并减少重复显著?
您可以使用@each
:
$list: "one", "two", "three";
@each $item in $list {
.name-#{$cat} {
@include thumb-source;
background: url('../name-#{$cat}.png') no-repeat;
}
}
@each文档
如果类名是连续的,您最好使用实际数字,这样您可以使用@for
循环。
$total: 4;
@for $i from 1 to $total {
.name-#{$i} {
@include thumb-source;
background: url('../name-#{$i}.png') no-repeat;
}
}
我还会为每个项目添加一个类,这样你就不需要在每个项目上添加@include thumb-source;
。这条船真大。
<div class="name name-1"></div>
<div class="name name-2"></div>
<div class="name name-3"></div>
那么做:
$total: 4;
.name {
@include thumb-source;
background-repeat: no-repeat;
@for $i from 1 to $total {
&.name-#{$i} {
background-image: url('../name-#{$i}.png');
}
}
}