带索引的@each循环

时间:2013-02-28 22:13:03

标签: sass each

我想知道你是否可以获得@each循环的元素索引。

我有以下代码,但我想知道$i变量是否是执行此操作的最佳方式。

当前代码:

$i: 0;
$refcolors: #55A46A, #9BD385, #D9EA79, #E4EE77, #F2E975, #F2D368, #F0AB55, #ED7943, #EA4E38, #E80D19;

@each $c in $refcolors {
    $i: $i + 1;
    #cr-#{$i} strong {
        background:$c;
    }   
}

3 个答案:

答案 0 :(得分:91)

首先,@each函数不是来自Compass,而是来自Sass。


要回答你的问题,每个循环都无法做到这一点,但很容易将其转换为@for循环,这可以做到这一点:

@for $i from 1 through length($refcolors) {
    $c: nth($refcolors, $i);

    // ... do something fancy with $c
}

答案 1 :(得分:51)

要更新此答案:是的,您可以使用@each循环实现此目的:

$colors-list: #111 #222 #333 #444 #555;

@each $current-color in $colors-list {
    $i: index($colors-list, $current-color);
    .stuff-#{$i} { 
        color: $current-color;
    }
}

来源:http://12devs.co.uk/articles/handy-advanced-sass/

答案 2 :(得分:12)

有时您可能需要使用数组或地图。我有一系列数组,即:

$list = (('sub1item1', 'sub1item2'), ('sub2item1', 'sub2item2'));

我发现将它转换为对象最简单:

$list: (
    'name': 'thao',
    'age': 25,
    'gender': 'f'
);

并使用以下内容获取$i

@each $property, $value in $list {
    $i: index(($list), ($property $value));

sass团队也推荐了以下内容,虽然我并不是一个粉丝:

  

[...]以上代码是我想解决的问题。通过添加范围($ n)等Sass函数可以提高效率。所以范围(10)=> (1,2,3,4,5,6,7,8,9,10)。然后枚举可以成为:

@function enumerate($list-or-map) {
    @return zip($list-or-map, range(length($list-or-map));
}

link.

相关问题