1

我有两个 SCSS 地图调用$my-map-1$my-map-2. 每个地图都有带有十六进制值的键。我编写了一个函数来分别返回每个映射的键和十六进制值($key, $value)。

之后,我@if用我的函数写了一个条件来检查地图。我将我的地图名称传递给函数。如果在那里映射,则检查是否$key等于给定名称。如果这是真的,请将其传递$valu$key我的颜色混合。这是我的代码。

$my-map-1: (
        map-1-color-1: #506c89,
        map-1-color-2: #737373,
        map-1-color-3: #2a3949,
        map-1-color-4: #182028,
);

$my-map-2: (
        map-2-color-1: #fff,
        map-2-color-2: #000,
        map-2-color-3: #ddd,
        map-2-color-4: #ccc,
);

//the function to read te map and return the key and the value.
@function color-map($color-map) {
  @each $key, $value in $color-map {    
    @return ($key, $value);
  }
}

//mixin
@mixin color-mix($color){
  color: $color;
}

//css classes from here
@if color-map($my-map-1) {
  if($key == map-1-color-1) {
    .my-class{
      @include color-mix($color:$value);
    }
  }
}
4

1 回答 1

1

您可以使用map-get方法,它非常有用:http ://sass-lang.com/documentation/Sass/Script/Functions.html#map_get-instance_method

这是一个混合的例子。我还将您的密钥作为参数传递:也许更好,因为您还可以检查其他密钥名称,如果您需要它:

$my-map-1: (
  map-1-color-1: #506c89,
  map-1-color-2: #737373,
  map-1-color-3: #2a3949,
  map-1-color-4: #182028
);

$my-map-2: (
  map-2-color-1: #fff,
  map-2-color-2: #000,
  map-2-color-3: #ddd,
  map-2-color-4: #ccc
);


@mixin color-map($color-map, $key-map) {
  @each $key, $value in $color-map {    
    @if($key == $key-map) {
      .my-class{
        color: map-get($color-map, $key);
      }
    }
  }
}

@include color-map($my-map-1, map-1-color-1); 

您的输出将是:

.my-class {
  color: #506c89;
}
于 2018-12-22T10:40:41.670 回答