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;
}
虽然使用会更简洁()
这样的函数:
$text-color: if($colorscheme == white, #333, #ccc);
$background-color: if($colorscheme == white, #fff, #333);