【问题标题】:How to Find the SCSS Index of the element in the list?如何查找列表中元素的 SCSS 索引?
【发布时间】:2019-04-08 21:04:33
【问题描述】:

我正在研究 SCSS 循环,但遇到了一个问题。问题是考虑颜色列表。

$colors:'red','green','red','blue';

@each $color in $colors{
  $i:index($colors,$color);
  .cube:nth-child(#{$i}){
    background:$color;
  };
}

上述程序的输出是

.cube:nth-child(1) {
  background: "red";
}

.cube:nth-child(2) {
  background: "green";
}

.cube:nth-child(1) { // issue here unable to get index value 3
  background: "red"; 
}

.cube:nth-child(4) {
  background: "blue";
}

我无法获得索引值 3。有人可以帮我解决这个问题吗? 我的问题是

  1. 如何获取索引值3?
  2. 是否可以使用 each 获取索引?如果“是”怎么办?
  3. 如果不是,还有什么替代方法?

【问题讨论】:

  • 您希望cube 的颜色作为颜色列表(在同一索引中)吗?
  • 是的,我需要使用循环获取索引值 3。
  • 好的,但是在 index=1 中颜色会在 2 绿色中变为红色...?
  • 我正在为我的背景颜色使用硬编码值。我只想要索引值。现在离开背景颜色。

标签: html css web sass frontend


【解决方案1】:

这是你需要的:

$colors:'red','green','red','blue';

@for $i from 1 through length($colors) {
  $color: nth($colors, $i);
  .cube:nth-child(#{$i}){
    background:$color;
  };
}

您的失败导致index($colors,$color) 将始终返回元素的第一个位置:Read ->http://sass-lang.com/documentation/Sass/Script/Functions.html#index-instance_method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2013-07-26
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多