javascript - 将函数 random() 与 sass 一起使用来选择随机变量

标签 javascript html css sass

我的 Scss 文件中有以下变量:

$flat-blue: #42a5f5;
$flat-green: #26a69a;
$flat-orange: #ffa727;
$flat-red: #ef5350;
$flat-purple: #c561d6;

我找到了一个 CodePen here改变两个数字之间的随机值,它似乎工作得很好。

有没有办法使用这个随机函数来选择我的变量之一?

我的 CSS:

.avatar {
    width: 43px;
    height: 43px;
    border-radius: 50%;
    overflow: hidden;
    z-index: 1;
    position: relative;
    background: $flat-green; //here should be the result of this function
    float: left;
    text-align: center;
    line-height: 43px;
    font-size: 20px;
    color:white;
    font-weight: lighter;
    text-transform: uppercase;
}

我的 HTML 结构:

<article data-value="<%= subscriber[:id] %>"
       data-status="<%= subscriber[:status] %>"
       data-user="<%= subscriber[:subscriber][:user_id] %>"
       data-profile="<%= subscriber[:profile_id] %>">
<div class="bg">
    <div class="avatar">
        <%= avatar_url(subscriber.profile.user.avatar, subscriber[:subscriber][:name]) %>
    </div>
</div>
</article>

最佳答案

这不是“随机”,但它会获取您在 sass 中定义的颜色列表,并将 .avatar:nth-child(n) 分配给该列表中的第 n 种颜色.因此,只要您定义的颜色至少与头像的数量一样多,每个人都会获得一种独特的颜色。如果您的头像多于颜色,这只会重复循环显示颜色。

$avatarBgColors: #42a5f5, #26a69a, #ffa727, #ef5350, #c561d6;

@for $i from 1 through length($avatarBgColors) {
  .avatar:nth-child(#{length($avatarBgColors)}n + #{$i}) {
    background-color: nth($avatarBgColors, $i);
  }
}

编译成:

.avatar:nth-child(5n + 1) {
  background-color: #42a5f5;
}
.avatar:nth-child(5n + 2) {
  background-color: #26a69a;
}
.avatar:nth-child(5n + 3) {
  background-color: #ffa727;
}
.avatar:nth-child(5n + 4) {
  background-color: #ef5350;
}
.avatar:nth-child(5n + 5) {
  background-color: #c561d6;
}

关于javascript - 将函数 random() 与 sass 一起使用来选择随机变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41040686/

相关文章:

javascript - 如何在 Kotlin for Javascript 中为类设置静态属性

JavaScript振动脚本修改

html - 如果字段集的显示是网格,图例元素是网格项吗?

css - 如何让div把剩下的地方全部填满?

html - 避免在鼠标悬停时颤动

javascript - 边界框外观 - 使用 fabricjs 控制自定义

javascript - Kris Kowal 的设计 promise 文章

javascript:按字符串中给定域(子字符串)查找完整 URL 的最快方法

html - 如何将背景图像设置为伪元素?

javascript - onfocus 关闭图标应显示在右侧