2014-11-14 51 views
7

我想指定一組顏色,然後將顏色隨機應用於列表。Sass中陣列的隨機顏色

到目前爲止,我擁有它,以便顏色順序循環。

我該如何隨機化它?

這是迄今爲止薩斯代碼:

$colors: red, orange, yellow, green, blue, purple; 

@for $i from 1 through length($colors) { 
    li:nth-child(#{length($colors)}n+#{$i}) { 
     background: lighten(nth($colors, $i), 20%); 
    } 
} 

li { 
    list-style: none; 
    padding: 1em; 
} 

和標記:在Codepen

<ul> 
    <li>a</li> 
    <li>b</li> 
    <li>c</li> 
    <li>d</li> 
    <li>e</li> 
    <li>f</li> 
    <li>g</li> 
    <li>h</li> 
    <li>i</li> 
    <li>j</li> 
    <li>k</li> 
    <li>l</li> 
</ul> 

例子: http://codepen.io/anon/pen/azbwJm

回答

9

首先,我應當提醒大家閱讀Sass被預編譯爲CSS;您無法使用Sass在「運行時」(即在頁面加載時)實現隨機行爲。

薩斯有您可能感興趣的隨機()函數:

$colors: red, orange, yellow, green, blue, purple; 
$repeat: 20 // How often you want the pattern to repeat. 
// Warning: a higher number outputs more CSS. 

@for $i from 1 through $repeat { 
    li:nth-child(#{length($colors)}n+#{$i}) { 
     background: lighten(nth($colors, random(length($colors))), 20%); 
    } 
} 

li { 
    list-style: none; 
    padding: 1em; 
} 

此選擇你$colors陣列的隨機指標和使用相關聯的顏色。

值得注意的一點是:在Sass documentation指出random($limit) 「[返回] 1 $limit之間的整數,包括1,但不$limit」。但是,如果在CodePen演示中使用nth($colors, random(length($colors) + 1))來「彌補」random()函數而不是選擇最高索引,則可能會因使用索引超出範圍而出現錯誤。這表明random()確實包括$limit

+0

完美地工作。 –