【问题标题】:Using function random() with sass to choose random variables使用带有 sass 的函数 random() 来选择随机变量
【发布时间】:2021-10-01 03:50:34
【问题描述】:

我的 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>

【问题讨论】:

  • 将所有这些颜色放入单个数组列表中,然后将 random() 函数与 nth() 一起使用不是更容易吗?
  • @clive 我该怎么做?
  • @Harry 我该怎么做?
  • @vbotio: 类似this?
  • 阅读文档,试一试,如果/当你遇到问题时,用代码更新问题

标签: javascript html css sass


【解决方案1】:

这不是“随机的”,但它会采用您在 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;
}

【讨论】:

  • 没有用。所有头像的颜色都相同:/
  • 它对我有用。您是否检查过 SASS 是否正确编译为 CSS?你的头像不是像你最初说的那样实际上是彼此的兄弟姐妹吗(在这种情况下,需要更改第 n 个孩子的结构)?
  • 是的,它正在正确编译,是的,它们是兄弟姐妹。我该怎么办?
  • 请编辑您的问题以显示 HTML 结构,或创建一个代码笔来演示该问题。
  • 这是我的小提琴,证明它有效:jsfiddle.net/md4pvgcz
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 2023-04-06
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多