Sass中数组中的随机颜色\[重复\]

随机 CSS

蛋蛋

2020-04-03

我想指定颜色数组,然后将颜色随机应用于列表。

到目前为止,我已经有了它,以便颜色可以按顺序循环显示。

如何将其随机化?

到目前为止,这是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

第3915篇《Sass中数组中的随机颜色\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
斯丁小小 2020.04.03

编辑: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)),则可能会因使用超出范围的索引而导致错误。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android