使用mixin参数作为变量

时间:2019-09-20 13:01:58

标签: css sass scss-mixins

所以我有不同的变量,并希望根据我给出的参数(这也是一个变量)生成css。

我想使用给定的参数作为变量名。 F.e.当给定primary作为参数时,我实际上想获取变量$ primary-brighter的值。

例如:

$primary: #f5f5f5;
$primary-brighter: #fff;

$secondary: #000;
$secondary-brighter: #333;

Mixin:

@mixin button-style($argument) {

 background: $argument
 color: $argument-brighter
}

使用中:

.button-primary {
 @include button-style(primary)
}

我希望得到什么:

.button-primary {
 background: #f5f5f5;
 color: #fff
}

我得到的是:

Error or
.button-primary {
 background: primary-brighter
}

我是否需要对参数进行转义以将其用作变量? ? 还是我的方法完全错误?

1 个答案:

答案 0 :(得分:1)

不确定是否有更清洁的方法,但是您可以使用maps来达到类似目的。一种方法是将按钮类定义为地图的键,其中包含要使用的另一种实际颜色的地图:

$button-colors: (

  "primary": (
    background: #f5f5f5,
    color: #fff
  ),

  "secondary": (
    background: #000,
    color: #333
  )

);

然后在您的$argument混音中将是文本值而不是十六进制值,并且您可以访问按钮颜色图:

@mixin button-style($argument) {

  $color-map: map-get($button-colors, $argument);

  background: map-get($color-map, background);
  color: map-get($color-map, color);

}

然后将混合消费如下:

.button-primary {
 @include button-style(primary)
}

.button-secondary {
 @include button-style(secondary)
}