@each loop with index

2019-01-31 02:45发布

I was wondering if you can get an element index for the @each loop.

I have the following code, but I was wondering if the $i variable was the best way to do this.

Current code:

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

标签: sass each
3条回答
萌系小妹纸
2楼-- · 2019-01-31 03:03

To update this answer: yes you can achieve this with the @each loop:

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

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

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-31 03:06

Sometimes you may need to use an array or a map. I had an array of arrays, i.e.:

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

I found that it was easiest to just convert it to an object:

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

And use the following to get $i:

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

The sass team also recommended the following, although I'm not much of a fan:

[...] The above code is how I'd like to address this. It can be made more efficient by adding a Sass function like range($n). So that range(10) => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Then enumerate can become:

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

link.

查看更多
Deceive 欺骗
4楼-- · 2019-01-31 03:09

First of all, the @each function is not from Compass, but from Sass.


To answer your question, this cannot be done with an each loop, but it is easy to convert this into a @for loop, which can do this:

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

    // ... do something fancy with $c
}
查看更多
登录 后发表回答