2011-03-29 95 views
15

我在跨範圍的Sass中使用變量默認值時遇到問題。我測試的例子是: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被定義爲「紅色」默認情況下,混入FOO!我預計導入mixin會將$ val設置爲「紅色」,除非已經定義。但是,在class1中,$ val在本地定義爲「綠色」,導入mixin foo時將其用「紅色」覆蓋。在其他類中,在將$ val全局定義爲「黑色」之後,按預期導入mixin作品,$ val保留其已定義的值。

我在做什麼錯?

回答

21

在class1中本地定義$val: 'green'不會在mixin中更改$val: 'red' !default,因爲它查找全局$ val。此時,沒有定義全局$ val。

然後全局$ val被定義爲'黑'。在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' 
+3

就像沒有'var'語句的JavaScript一樣! ......該死的。 – iono 2012-11-30 05:11:24

+1

非常討厭的行爲和SASS團隊從JS,IMho借用此範圍的奇怪決定。 – MoMolog 2013-06-14 15:52:39