我编写了以下循环来遍历团队列表,以生成精灵图像的背景位置。如何将其转换为函数,以便我可以传入$ teams,$ X和$ Y值?
$teams: A, B, C, D;
$x: 0;
$y: 0;
@each $team in $teams {
$i: index($teams, $team);
$y: $y + 20px;
.team#{$team}:before,
.team#{$team}:after {
background-position: $x $y;
}
}
输出:
.teamA:before,
.teamA:after {
background-position: 0 20px;
}
.teamB:before,
.teamB:after {
background-position: 0 40px;
}
.teamC:before,
.teamC:after {
background-position: 0 60px;
}
.teamD:before,
.teamD:after {
background-position: 0 80px;
}
我面临的另一个问题是某些团队会分享相同的背景位置,因此所需的输出会是这样的:
.teamA:before,
.teamA:after,
.teamAB:before,
.teamAB:after {
background-position: 0 20px;
}
.teamB:before,
.teamB:after {
background-position: 0 40px;
}
.teamC:before,
.teamC:after
.teamCB:before,
.teamCB:after {
background-position: 0 60px;
}
.teamD:before,
.teamD:after {
background-position: 0 80px;
}
是否可以通过某些分隔符对团队名称进行分组,以便将其编译到同一共享属性中?
$teams: 'A AB', B, 'CB, C', D;
答案 0 :(得分:0)
您可以检查当前索引是列表还是值。如果它是一个值,请执行您已经在做的事情。如果它是一个元组,则遍历每个元组,将每个位置设置为相同的值(如果它是最外层列表上的新索引,则仅更改数值)。
$teams: A AB, B, CB C, D;
$x: 0;
$y: 0;
@each $team in $teams {
$y: $y + 20px;
@if type-of($team) == list {
@each $team-sub in $team {
.team#{$team-sub}:before,
.team#{$team-sub}:after {
background-position: $x $y;
}
}
}
@else {
.team#{$team}:before,
.team#{$team}:after {
background-position: $x $y;
}
}
}
我已经对此进行了测试,并且按预期工作。
编辑:这是使用复合选择器的更新版本。这将在未来从SASS中删除,因此使用风险自负。
$teams: A AB, B, CB C, D;
$x: 0;
$y: 0;
@each $team in $teams {
$y: $y + 20px;
@if type-of($team) == list {
@each $team-sub in $team {
$i: index($team, $team-sub);
@if $i == 1 {
.team#{$team-sub}::before,
.team#{$team-sub}::after {
background-position: $x $y;
}
}
@else {
.team#{$team-sub}::before {
@extend .team#{nth($team, 1)}::before;
}
.team#{$team-sub}::after {
@extend .team#{nth($team, 1)}::after;
}
}
}
}
@else {
.team#{$team}::before,
.team#{$team}::after {
background-position: $x $y;
}
}
}