SASS忽略在if语句中定义的变量 [英] SASS ignores variables, defined in if-statement

查看:679
本文介绍了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);

这篇关于SASS忽略在if语句中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆