SASS 忽略在 if 语句中定义的变量
我有一个名为 style.scss 的文件,代码如下:
I have one file named style.scss with the following code:
@import 'variables';
body {
color: $text-color;
background: $background-color;
}
还有一个名为 _variables.scss 的部分:
And one partial named _variables.scss:
$colorscheme: white;
@if $colorscheme == white {
$text-color: #333;
$background-color: #fff;
}
@else {
$text-color: #ccc;
$background-color: #333;
}
if 语句正常工作,但内部定义的变量不起作用.当我尝试编译它时,我不断收到:
The if-statement works properly, but the variables defined inside, do not work. When I try to compile it, I keep getting:
语法错误:未定义变量:$text-color".
Syntax error: Undefined variable: "$text-color".
这完全在意料之中.变量有一个作用域.如果您在控制块内定义它们(如 if
语句),则它们在外部将不可用.所以,你需要做的是像这样在外面初始化它:
That's completely expected. Variables have a scope to them. If you define them inside of a control block (like an if
statement), then they won't be available outside. So, what you need to do is initialize it outside like so:
$text-color: null;
$background-color: null;
@if $colorscheme == white {
$text-color: #333;
$background-color: #fff;
}
@else {
$text-color: #ccc;
$background-color: #333;
}
或者...
$text-color: #ccc;
$background-color: #333;
@if $colorscheme == white {
$text-color: #333;
$background-color: #fff;
}
虽然像这样使用 if()
函数会不那么冗长:
Though it would be less verbose to use the if()
function like this:
$text-color: if($colorscheme == white, #333, #ccc);
$background-color: if($colorscheme == white, #fff, #333);