【问题标题】:@each loop with index@each 带索引的循环
【发布时间】:2013-02-15 07:16:48
【问题描述】:

我想知道您是否可以获得@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;
    }   
}

【问题讨论】:

    标签: sass each


    【解决方案1】:

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

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

    我发现将其转换为对象是最简单的:

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

    并使用以下获取$i

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

    sass 团队还推荐了以下内容,虽然我不太喜欢:

    [...] 上面的代码是我想解决这个问题的方式。通过添加像 range($n) 这样的 Sass 函数可以提高效率。所以 range(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.

    【讨论】:

      【解决方案2】:

      要更新此答案:是的,您可以使用 @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/

      【讨论】:

      • 不幸的是,如果 $colors-list 包含 2 个相同的值(例如 #111、#222、#111、#333),这种方法就会失效。在这种情况下 index($colors-list, #111) 将始终返回 1,因此您的 $i 值将显示为 1, 2, 1, 4。否则这是一种非常巧妙的方法:)
      • 这也是 1-indexed 而不是常见的 0-index
      【解决方案3】:

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


      要回答您的问题,这不能通过 each 循环来完成,但很容易将其转换为 @for 循环,可以这样做:

      @for $i from 1 through length($refcolors) {
          $c: nth($refcolors, $i);
      
          // ... do something fancy with $c
      }
      

      【讨论】:

        猜你喜欢
        • 2012-09-27
        • 2014-10-29
        • 1970-01-01
        • 2012-03-07
        • 2015-11-12
        • 1970-01-01
        • 2019-03-16
        • 1970-01-01
        • 2020-04-06
        相关资源
        最近更新 更多