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

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

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

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