Sass中阵列的随机颜色

Nia*_*son 12 random sass

我想指定一个颜色数组,然后将颜色随机应用到列表中.

到目前为止,我已经拥有它,以便颜色按顺序循环.

我该如何随机化呢?

这是迄今为止的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;
}
Run Code Online (Sandbox Code Playgroud)

和标记:

<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>
Run Code Online (Sandbox Code Playgroud)

Codepen上的示例:http://codepen.io/anon/pen/azbwJm

小智 17

首先,我应该提醒大家阅读Sass预编译成CSS; 您无法使用Sass在"运行时"(即在页面加载时)实现随机行为.

Sass有一个random()函数,你可能会感兴趣:

$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;
}
Run Code Online (Sandbox Code Playgroud)

这会选择$colors数组的随机索引并使用相关的颜色.

有趣的说明:Sass文档声明random($limit)"[返回] 1 $limit到1 之间的整数,包括1但不是$limit." 但是,如果您nth($colors, random(length($colors) + 1))在CodePen演示中使用"弥补" random()不选择最高索引的函数,则使用索引超出界限时可能会出错.这表明random()确实包括$limit.