ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
Sass 中变量的作用域在过去几年已经发生了一些改变。直到最近,规则集和其他范围内声明变量的作用域才默认为本地。如果已经存在同名的全局变量,则局部变量覆盖全局变量。从 Sass 3.4 版本开始,Sass 已经可以正确处理作用域的概念,并通过创建一个新的局部变量来代替。 本部分讨论下**全局变量的影子**。当在局部范围内(选择器内、函数内、混合宏内……)声明一个已经存在于全局范围内的变量时,局部变量就成为了全局变量的_影子_。基本上,局部变量只会在局部范围内覆盖全局变量。 以下代码片可以解析**变量影子**的概念。 ~~~ // Initialize a global variable at root level. $variable: 'initial value'; // Create a mixin that overrides that global variable. @mixin global-variable-overriding { $variable: 'mixin value' !global; } .local-scope::before { // Create a local variable that shadows the global one. $variable: 'local value'; // Include the mixin: it overrides the global variable. @include global-variable-overriding; // Print the variable’s value. // It is the **local** one, since it shadows the global one. content: $variable; } // Print the variable in another selector that does no shadowing. // It is the **global** one, as expected. .other-local-scope::before { content: $variable; } ~~~