Random Sass中数组的随机颜色

Random Sass中数组的随机颜色,random,sass,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($colo

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

到目前为止,我有它,这样的颜色将循环通过顺序

我怎样才能随机化呢

以下是迄今为止的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;
}
以及标记:

<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>
  • a
  • b
  • c
  • d
  • e
  • f
  • g
  • h
  • j
  • k
  • l
代码笔示例:

编辑:Sass引入了模块系统。
random()
函数正在转换为
math.random()
。有关更多信息,请参阅和文档


首先,我应该提醒大家,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;
}
这将选择
$colors
数组的随机索引,并使用关联的颜色

注意:文档说明
random($limit)
“返回一个介于1和
$limit
之间的随机整数”。这包括
$limit
作为一个可能的值。因此,如果使用
nth($colors,random(length($colors)+1))
,则使用索引超出范围时可能会出错