这个问题在这里已经有了答案:
SASS: randomly pick background-image from a list
(1 个回答)
6年前关闭。
我想指定一个颜色数组,然后将颜色随机应用于列表。
到目前为止,我拥有它,以便颜色按顺序循环。
我怎样才能随机化它?
到目前为止,这是 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>
Codepen 上的示例:
http://codepen.io/anon/pen/azbwJm
最佳答案
编辑 : Sass 引入了模块系统。 random()
函数正在转换到 math.random()
.请参阅 the function 的文档对于 the module system了解更多信息。
首先,我要提醒所有阅读 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))
,您可能会因使用超出范围的索引而出错。
关于Sass中数组的随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922336/