如何分配给 Sass 中的全局变量? [英] How to assign to a global variable in Sass?

查看:69
本文介绍了如何分配给 Sass 中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行这个 Sass 代码:

I run this Sass code:

$a: 1;
@if 2 + 2 == 4 {
    $a: 2;
}
@debug $a;

我希望看到 2.然而,输出是:

I expect to see 2. The output, however, is:

Line 5 DEBUG: 1

我知道 Sass 在 @if 范围内创建了一个新的 $a 变量.如何更改此行为并为全局 $a 赋值?

I understand that Sass creates a new $a variable inside the @if scope. How can I change this behaviour and assign a value to the global $a?

我使用 Sass 3.4.0.

I use Sass 3.4.0.

推荐答案

当您使用 Sass 3.4+ 时,您应该将 !global 标志附加到您的变量声明中:

As you're using Sass 3.4+, you should append the !global flag to your variable declaration:

$a: 1;
@if 2 + 2 == 4 {
    $a: 2 !global;
}
@debug $a; // will output 2

关于变量声明的原始 SASS_REFERENCE 声明:

The original SASS_REFERENCE on variable declaration stated:

"变量仅在嵌套选择器级别内可用它们被定义的地方.如果它们是在任何嵌套之外定义的选择器,它们随处可用.

"Variables are only available within the level of nested selectors where they're defined. If they're defined outside of any nested selectors, they're available everywhere.

但是 3.4+ 的 SASS_CHANGELOG 表明这种行为已经改变:

but the SASS_CHANGELOG of 3.4+ shows that this behaviour has changed:

所有不在文档顶层的变量赋值现在默认为本地.如果有一个同名的全局变量,它除非使用 !global 标志,否则不会被覆盖.

All variable assignments not at the top level of the document are now local by default. If there’s a global variable with the same name, it won’t be overwritten unless the !global flag is used.

例如,$var: value !global 将全局分配给 $var.可以使用 feature-exists(global-variable-shadowing) 检测这种行为.

For example, $var: value !global will assign to $var globally. This behavior can be detected using feature-exists(global-variable-shadowing).

这篇关于如何分配给 Sass 中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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