Sass如何访问变量'名单

时间:2017-02-15 06:41:10

标签: css sass

$red:"#111", "#222", "#333";
$orange: "#444", "#555","#666";
$green: "#777","#888","#999";

$color-collection: $red, $orange, $green;

@each $color in $color-collection {
    .color  {
        @for $i from 1 through length($color-collection) {
      $c: nth($color-collection, $i);
        .colours--#{$i} {
             background: $c;
          }
       }
    }
}

输出打印所有颜色,

.color .colours--1 {
  background: "#111", "#222", "#333";
}
.color .colours--2 {
  background: "#444", "#555", "#666";
}
.color .colours--3 {
  background: "#777", "#888", "#999";
}

我想打印为@each,以及如何访问$color-collection' s $red?看起来不像$color-collection[$red]

我想打印如下

.color .colours--1 {
  background: "#111";
}
.color .colours--2 {
  background: "#222";
}
.color .colours--3 {
  background: "#333";
}

等等

3 个答案:

答案 0 :(得分:2)

你几乎就在那里,我已经稍微修改了你的代码以获得你想要的结果!

You can view the working demo here.

$red:"#111", "#222", "#333";
$orange: "#444", "#555","#666";
$green: "#777","#888","#999";

$color-collection: $red, $orange, $green;

@each $color in $color-collection {
  .color  {
    @for $i from 1 through length($color-collection) {
      $c: nth($color, $i);
      .colours--#{$i} {
           background: $c;
      }
    }
  }
}

虽然这确实回答了你的问题,但在它的当前设置中,每个循环都会覆盖前一个类,所以请注意这一点......

答案 1 :(得分:1)

这会让你走上正确的道路。

我用来做的是使用mapsmap-get属性,如下所示:

@function color($collection, $key) {
  @if map-has-key($collection, $key) {
    @return map-get($collection, $key);
  }

  @warn "Unknown `#{$key}` in $collection.";

  @return null;
}

$red: "#111", "#222", "#333";
$orange: "#444", "#555", "#666";
$green: "#777", "#888", "#999";

$colorcollection: (red: $red, orange: $orange, green: $green); 

.element {
color: color($colorcollection, red);
}

你只需要为颜色中的每个元素重复句子,就能达到你想要的目标。

您可以在此处查看运行示例: Sassmeister example

答案 2 :(得分:0)

试一试:

$red: "#111", "#222", "#333";
$orange: "#444", "#555", "#666";
$green: "#777", "#888", "#999";

$color-collection: join($red, $orange);
$color-collection: join($color-collection, $green);

@each $color in $color-collection {
    .color  {
        @for $i from 1 through length($color-collection) {
      $c: nth($color-collection, $i);
        .colours--#{$i} {
             background: $c;
          }
       }
    }
}

这完全符合您的要求,但它根本无法很好地扩展。

您需要将列表一起加入一个列表而不是列表列表。