2009-10-02 63 views
8

我希望在if語句中定義變量可以在Sass中工作,但不幸的是,我收到錯誤,指出該變量未定義。這裏是我的嘗試:在if語句中聲明的變量導致「未定義的變量」

@for !i from 1 through 9 
    !foo = #000 
    @if !i == 1 
     !bg_color = #009832 
    @if !i == 2 
     !bg_color = #195889 
    ... 

    #bar#{!i} 
     color: #{!foo} 
     background-color: #{!bg_color} 

有了這個代碼,我會得到以下錯誤:

Undefined variable: "!bg_color".

回答

11

薩斯變量只能在聲明它們和那些下嵌套縮進的水平可見它。所以,你只需要聲明bg_color你之外的for循環:

!bg_color = #FFF 
@for !i from 1 through 9 
    !foo = #000 
    @if !i == 1 
     !bg_color = #009832 
    @if !i == 2 
     !bg_color = #195889 

    #bar#{!i} 
     color: #{!foo} 
     background-color: #{!bg_color} 

,你會得到下面的CSS:

#bar1 { 
    color: black; 
    background-color: #009832; } 

#bar2 { 
    color: black; 
    background-color: #195889; } 

#bar3 { 
    color: black; 
    background-color: #195889; } 

#bar4 { 
    color: black; 
    background-color: #195889; } 

#bar5 { 
    color: black; 
    background-color: #195889; } 

#bar6 { 
    color: black; 
    background-color: #195889; } 

#bar7 { 
    color: black; 
    background-color: #195889; } 

#bar8 { 
    color: black; 
    background-color: #195889; } 

#bar9 { 
    color: black; 
    background-color: #195889; } 
+0

我確信我試過了。謝謝。 – DEfusion 2009-10-04 17:25:50