所以我有不同的变量,并希望根据我给出的参数(这也是一个变量)生成 css。
我想使用给定的参数作为变量名。 F.e.当给定 primary 作为参数时,我实际上想获得变量 $primary-brighter 的值。
例如:
$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
}
我需要转义参数才能将其用作变量吗? ? 还是我的方法完全错误?
最佳答案
不确定是否有更简洁的方法,但您可以使用 maps 实现类似的效果.一种方法是将您的按钮类定义为一个 map 的键,该 map 包含要使用的实际颜色的另一个 map :
$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);
}
mixin 然后会像这样被消耗:
.button-primary {
@include button-style(primary)
}
.button-secondary {
@include button-style(secondary)
}
关于css - 使用 mixin 参数作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58028921/