【问题标题】:Is it possible to create a loop to cycle through a map however stop at a certain index in the map ? - SASS是否可以创建一个循环来循环遍历地图,但在地图中的某个索引处停止? - 萨斯
【发布时间】:2019-12-10 06:54:36
【问题描述】:

我有一个包含五种颜色的颜色主题图,我想创建一个 mixin 来接受一个作为停止点的数字参数。然后 mixin 将执行循环,但是当它到达 mixin 参数号时停止 map 循环。

试图阅读此内容,但找不到任何答案或解决方案来实现这一点。

代码示例:

// color map
$colors: (
 "r": red,
 "b": blue,
 "g": green,
 "y": yellow,
 "o": orange,
)

当前情况:每个循环在地图中不断循环,直到到达终点。因此它将创建 5 个选择器,它们的背景颜色作为地图中的值。

@mixin color_theme($map) {
  @each $col, $color in $map {
    &.#{$col} {
      background-color: $color;
    }
  }
}

目标:创建一个带有循环的 mixin,仅循环到地图中固定数量的值。

【问题讨论】:

    标签: css sass


    【解决方案1】:

    您可以使用index(相关答案:SASS - get map item value by item index)获取地图索引号,然后使用它在某个数字处停止循环:

    // color map
    $colors: (
     "r": red,
     "b": blue,
     "g": green,
     "y": yellow,
     "o": orange
    );
    
    @mixin color_theme($map, $stop) {
      @each $col, $color in $map {
        $i: index($map, $col $color);
        @if ($i <= $stop){
          &.#{$col} {
            background-color: $color;
          }
        }
      }
    }
    
    div{
      @include color_theme($colors, 4);
    }
    

    你的输出:

    div.r {
      background-color: red;
    }
    div.b {
      background-color: blue;
    }
    div.g {
      background-color: green;
    }
    div.y {
      background-color: yellow;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多