我正在尝试使用 darken
sass 函数,但是当我从我的 scss 模块中的 sass 对象读取时,它认为颜色实际上是一个字符串,因此该函数无法解析传递的变量中。
变量.scss
$primary: #ae9fec;
$secondary: #d19ac1;
$theme: (
"primary": ($primary, white),
"secondary": ($secondary, white)
);
Button.module.scss
@each $colorGroup in $theme {
&[data-variant="#{nth($colorGroup, 1)}"] {
background-color: #{nth(nth($colorGroup, 2), 1)}); // this works
&:hover {
background-color: darken(#{nth(nth($colorGroup, 2), 1)}), 10%); // this does not because it thinks its a string. I tried unquote() but that didn't work, still thinks it's a string.
}
}
}
最佳答案
如果您删除选择器规则中的插值(而不是选择器本身),它应该按预期进行编译。
这是一个测试 - 我假设您将 @each
循环嵌套在选择器中或使用 @at-root
,因为基本级规则不能包含像这样的 &
字符 - 为您的规则集使用 .button
选择器:
/* variables.scss */
$primary: #ae9fec;
$secondary: #d19ac1;
$theme: (
"primary": ($primary, white),
"secondary": ($secondary, white)
);
/* Button.module.scss */
.button {
@each $colorGroup in $theme {
&[data-variant="#{nth($colorGroup, 1)}"] {
background-color: nth(nth($colorGroup, 2), 1);
&:hover {
background-color: darken(nth(nth($colorGroup, 2), 1), 10%);
}
}
}
}
编译后的代码如下所示:
.button[data-variant="primary"] {
background-color: #ae9fec;
}
.button[data-variant="primary"]:hover {
background-color: #8a74e4; /* Darkened $primary */
}
.button[data-variant="secondary"] {
background-color: #d19ac1;
}
.button[data-variant="secondary"]:hover {
background-color: #c177ab; /* Darkened $secondary */
}
我还删除了示例中多余的括号。
关于SASS 函数变暗和变亮在使用颜色对象时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58490138/