我在跨范围内使用Sass中的变量默认值时遇到问题。我的测试示例是:
@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被定义为'red'!默认在mixin foo中。我希望导入mixin会将$ val设置为'red',除非它已经定义。但是,在class1中,$ val在本地定义为'green',导入mixin foo会用'red'覆盖它。在其他类中,在$ val的全局定义为“black”之后,导入mixin按预期工作,$ val保留其已定义的值。
我做错了什么?
答案 0 :(得分:21)
在class1中本地定义$val: 'green'
不会改变mixin中的$val: 'red' !default
,因为它会查找全局$ val。此时,没有定义全局$ val。
然后全局$ val被定义为'black'。在mixin中这个$ val之后寻找全球$ val。此时,全局$ val已被定义为“黑色”。
在本地再次定义$ val将改变已定义的全局$ val。
@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'