2017-07-27 41 views
2

我已经编写了以下循环来循环遍历团队列表以生成精灵图像的背景位置。我怎样才能把它变成一个函数,这样我就可以传入$组,$ X和$ Y的值了呢?将SASS中的背景位置列表映射为函数

$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

您可以检查当前索引是否是列表或值。如果这是一种价值,那就去做你现在正在做的事情。如果它是一个元组,遍历每一个元素,为每个元素设置相同的值(如果它是最外层列表中的新索引,则只更改数值)。

$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; 
    } 
    } 
} 
+0

是否有可能A和AB组到同一个组,如: '答:之前, 答:之后, AB:之前, AB:{...}' – calebo

+0

我不后不相信直线SCSS是可能的。它可能使用一个函数,但我不得不深入研究这个文档。不出所料,如果它们合并在一起,浏览器并不在乎。 – jhpratt

+1

我发现[this](https://stackoverflow.com/a/19088399/2718801)。当我有机会的时候,我会尽力将这两者混合在一起! – jhpratt