2017-02-15 56 views
0
$red:"#111", "#222", "#333"; 
$orange: "#444", "#555","#666"; 
$green: "#777","#888","#999"; 

$color-collection: $red, $orange, $green; 

@each $color in $color-collection { 
    .color { 
     @for $i from 1 through length($color-collection) { 
     $c: nth($color-collection, $i); 
     .colours--#{$i} { 
      background: $c; 
      } 
     } 
    } 
} 

輸出打印所有顏色,薩斯如何訪問變量列表

.color .colours--1 { 
    background: "#111", "#222", "#333"; 
} 
.color .colours--2 { 
    background: "#444", "#555", "#666"; 
} 
.color .colours--3 { 
    background: "#777", "#888", "#999"; 
} 

我想打印爲@each,所以如何訪問$color-collection$red?看起來不像這樣$color-collection[$red]

我想打印像下面

.color .colours--1 { 
    background: "#111"; 
} 
.color .colours--2 { 
    background: "#222"; 
} 
.color .colours--3 { 
    background: "#333"; 
} 

回答

2

你幾乎在那裏,我已經修改了你的代碼稍微得到的結果你是後!

You can view the working demo here.

$red:"#111", "#222", "#333"; 
$orange: "#444", "#555","#666"; 
$green: "#777","#888","#999"; 

$color-collection: $red, $orange, $green; 

@each $color in $color-collection { 
    .color { 
    @for $i from 1 through length($color-collection) { 
     $c: nth($color, $i); 
     .colours--#{$i} { 
      background: $c; 
     } 
    } 
    } 
} 

雖然這回答你的問題,在它的當前設置每個循環覆蓋以前的課,所以才意識到這一點......

0

這給一個鏡頭:

$red: "#111", "#222", "#333"; 
$orange: "#444", "#555", "#666"; 
$green: "#777", "#888", "#999"; 

$color-collection: join($red, $orange); 
$color-collection: join($color-collection, $green); 

@each $color in $color-collection { 
    .color { 
     @for $i from 1 through length($color-collection) { 
     $c: nth($color-collection, $i); 
     .colours--#{$i} { 
      background: $c; 
      } 
     } 
    } 
} 

這正是你想要的,然而它不會很好地擴展。

您需要將列表一起加入到一個列表中,而不是列表的列表中。

1

這會讓你走上正確的道路。

我用什麼做的,就是用mapsmap-get財產,像這樣:

@function color($collection, $key) { 
    @if map-has-key($collection, $key) { 
    @return map-get($collection, $key); 
    } 

    @warn "Unknown `#{$key}` in $collection."; 

    @return null; 
} 

$red: "#111", "#222", "#333"; 
$orange: "#444", "#555", "#666"; 
$green: "#777", "#888", "#999"; 

$colorcollection: (red: $red, orange: $orange, green: $green); 

.element { 
color: color($colorcollection, red); 
} 

你只需要重複這句話對每個元素的顏色,以達到你想要什麼要得到。

您可以在此處看到運行示例: Sassmeister example