Css 使用mixin参数作为变量
因此,我有不同的变量,并希望根据我给出的参数(也是一个变量)生成css 我想使用给定的参数作为变量名。F.e.当作为参数给出primary时,我实际上想要得到变量$primary的值 例如:Css 使用mixin参数作为变量,css,sass,scss-mixins,Css,Sass,Scss Mixins,因此,我有不同的变量,并希望根据我给出的参数(也是一个变量)生成css 我想使用给定的参数作为变量名。F.e.当作为参数给出primary时,我实际上想要得到变量$primary的值 例如: $primary: #f5f5f5; $primary-brighter: #fff; $secondary: #000; $secondary-brighter: #333; 混合: @mixin button-style($argument) { background: $argument c
$primary: #f5f5f5;
$primary-brighter: #fff;
$secondary: #000;
$secondary-brighter: #333;
混合:
@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
}
我是否需要转义参数以将其用作变量?
还是我的方法完全错了?不确定是否有更干净的方法,但你可以用它来实现这样的目标。一种方法是将按钮类定义为地图的键,该键包含另一个实际使用颜色的地图:
$button-colors: (
"primary": (
background: #f5f5f5,
color: #fff
),
"secondary": (
background: #000,
color: #333
)
);
然后在mixin中,$参数将是文本值而不是十六进制值,您可以访问按钮颜色映射:
@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)
}
@由于某种原因,我没有考虑将变量作为十六进制值传入,所以这是有意义的。不幸的是,当时这种方法行不通。我用一种使用地图的方法更新了我的答案。它能用,但不太干净。