@each loop with index

与世无争的帅哥 提交于 2019-11-29 20:33:30
Wouter J

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
}

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/

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!