Sass中数组的随机颜色 [英] Random color from array in Sass

查看:134
本文介绍了Sass中数组的随机颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to specify an array of colours and then apply the colors randomly to a list.

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

So far I have it so that the colors will cycle through in order.

如何将其随机化?

这是到目前为止的Sass代码:

Here is the Sass code so far:

$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

Example on Codepen: http://codepen.io/anon/pen/azbwJm

推荐答案

编辑:Sass引入了模块系统. random()功能正在过渡到math.random().请参见函数

Edit: Sass introduced a module system. The random() function is transitioning to math.random(). See the documentation for the function and for the module system for more information.

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

First, I should state a reminder to everyone reading that Sass is precompiled into CSS; you cannot achieve random behavior "at runtime" (i.e. on page load) using Sass.

Sass的random()功能可能会让您感兴趣:

Sass has a random() function that might interest you:

$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数组的随机索引并使用相关的颜色.

This chooses a random index of your $colors array and uses the associated color.

注意:文档指出random($limit)返回1到$limit之间的随机整数".这包括$limit作为可能的值.因此,如果使用nth($colors, random(length($colors) + 1)),则可能会因使用超出范围的索引而出错.

Note: the documentation states that random($limit) "returns a random whole number between 1 and $limit." This includes $limit as a possible value. As a result, if you use nth($colors, random(length($colors) + 1)), you are liable to get an error for using an index out of bounds.

这篇关于Sass中数组的随机颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆