代码之家  ›  专栏  ›  技术社区  ›  Chandra Shekhar

如何在列表中找到元素的SCSS索引?

  •  1
  • Chandra Shekhar  · 技术社区  · 6 年前

    我正在处理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. 是否可以使用每种方法获取索引?如果“是”怎么办?
    3. 如果没有,还有什么办法?
    1 回复  |  直到 6 年前
        1
  •  5
  •   Dinca Adrian    6 年前

    这就是你需要的:

    $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