Sass变量的默认范围 [英] Sass variable default scope
问题描述
我在跨范围的Sass中使用变量默认值时遇到问题.我的测试示例是:
I have a problem with using variable defaults in Sass across scopes. My test example is:
@mixin foo {
$val: 'red' !default;
.bar {
color: $val;
}
}
@include foo;
.class1 {
$val: 'green';
@include foo;
.class11 {
@include foo;
}
}
$val: 'black';
.class2 {
@include foo;
}
.class3 {
$val: 'blue';
@include foo;
}
.class4 {
@include foo;
}
它编译为:
.bar {
color: "red";
}
.class1 .bar {
color: "red";
}
.class1 .class11 .bar {
color: "red";
}
.class2 .bar {
color: "black";
}
.class3 .bar {
color: "blue";
}
.class4 .bar {
color: "blue";
}
如您所见,变量$ val在mixin foo中定义为'red'!default.我希望导入mixin会将$ val设置为"red",除非它已经被定义.但是,在class1中,$ val在本地定义为绿色",导入mixin foo会将其覆盖为红色".在其他类中,在将$ val全局定义为黑色"之后,导入mixin可以按预期进行,并且$ val保留其已定义的值.
As you can see, variable $val is defined as 'red' !default in the mixin foo. I expect that importing the mixin would set $val to 'red' unless it is already defined. However, in class1, where $val is locally defined as 'green', importing the mixin foo overwrites it with 'red'. In other classes, after the global definition of $val as 'black', importing the mixin works as expected and $val retains its already defined value.
我在做什么错了?
推荐答案
在class1中本地定义$val: 'green'
不会更改mixin中的$val: 'red' !default
,因为它会寻找全局$ val.此时,尚未定义全局$ val.
Defining $val: 'green'
locally in class1 does not alter $val: 'red' !default
in mixin, because it look for global $val. At this point, no global $val has been defined.
然后将全局$ val定义为黑色".在mixin中的此$ val之后,寻找全局$ val.此时,全局$ val已被定义为黑色".
Then global $val is defined as 'black'. After this $val in mixin look for global $val. At this point, global $val has been defined as 'black'.
再次在本地定义$ val将更改已定义的全局$ val.
Defining $val again locally will alter global $val that has been defined.
@mixin foo
$val: 'red' !default // defined locally
.bar
color: $val
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
.class1
$val: 'green'
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
color: $val // local $val 'green'
.class11
@include foo // $val in mixin foo look for global $val. no global $val found, then 'red'
$val: 'black' // defined globally at the first time
.class2
@include foo // $val in mixin foo look for global $val. $val found, 'black'
.class3
$val: 'blue' // change the gobal $val
@include foo // $val in mixin foo look for global $val. $val found, 'blue'
.class4
@include foo // $val in mixin foo look for global $val. $val found, 'blue'
这篇关于Sass变量的默认范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!