2012-05-13 108 views
21

我有一大堆的元素: (#CP1,CP2#,#CP3,CP4#)for循環SCSS與變量組合

,我想背景顏色添加到使用SCSS 。

我的代碼是:

$colour1: rgb(255,255,255); // white 
$colour2: rgb(255,0,0); // red 
$colour3: rgb(135,206,250); // sky blue 
$colour4: rgb(255,255,0); // yellow 

@for $i from 1 through 4 { 
    #cp#{i} { 
     background-color: rgba($(colour#{i}), 0.6); 

     &:hover { 
      background-color: rgba($(colour#{i}), 1); 
      cursor: pointer; 
     } 
    } 
} 
+0

,什麼是錯的代碼? –

+2

@neosatan顏色拼寫錯誤; ;-) –

+4

@StenMuchow http://grammarist.com/spelling/color-colour/不能自己幫我 –

回答

14

SASS變量仍需要與內部插值美元符號作爲前綴,所以每次有#{i}的地方,它應該是#{$i}。你可以在SASS參考interpolations上看到其他例子。

41

除了使用插值生成變量名稱外,您可以創建一個列表並使用nth方法獲取值。爲了內插工作,語法應爲#{$i},如料斗所述。

$colour1: rgb(255,255,255); // white 
$colour2: rgb(255,0,0); // red 
$colour3: rgb(135,206,250); // sky blue 
$colour4: rgb(255,255,0); // yellow 

$colors: $colour1, $colour2, $colour3, $colour4; 

@for $i from 1 through length($colors) { 
    #cp#{$i} { 
     background-color: rgba(nth($colors, $i), 0.6); 

     &:hover { 
      background-color: rgba(nth($colors, $i), 1); 
      cursor: pointer; 
     } 
    } 
} 
+14

可能更好地獲取列表長度而不是硬編碼它:' @for $ i從1到length($ colors){...' – steveax

+0

當然,最好不要硬編碼長度。我應用了這個變化。謝謝steveax。 – Xabriel

+0

這個迴應應該被驗證。 – Sarcadass

28

正如@hopper曾表示,主要的問題是,你有沒有前綴插入變量以美元符號所以他的答案應該被標記爲正確的,但我想添加一個提示。

使用@each規則而不是@for循環爲這個特定案件。原因:

  • 你不需要知道列表的長度
  • 你並不需要使用length()函數來計算列表
  • 你並不需要使用的長度第n個()函數
  • @each規則比@for指令

代碼多個語義:

$colours: rgb(255,255,255), // white 
      rgb(255,0,0),  // red 
      rgb(135,206,250), // sky blue 
      rgb(255,255,0); // yellow 

@each $colour in $colours { 
    #cp#{$colour} { 
     background-color: rgba($colour, 0.6); 

     &:hover { 
      background-color: rgba($colour, 1); 
      cursor: pointer; 
     } 
    } 
} 

或者,如果你喜歡,你可以包括在@each指令,而不是申報$顏色變量中的每個$顏色:

$colour1: rgb(255,255,255); // white 
$colour2: rgb(255,0,0);  // red 
$colour3: rgb(135,206,250); // sky blue 
$colour4: rgb(255,255,0); // yellow 

@each $colour in $colour1, $colour2, $colour3, $colour4 { 
    #cp#{$colour} { 
     background-color: rgba($colour, 0.6); 

     &:hover { 
      background-color: rgba($colour, 1); 
      cursor: pointer; 
     } 
    } 
} 

Sass Reference for @each directive