【问题标题】:Sass each loop with an indexSass 每个循环都有一个索引
【发布时间】:2016-11-08 21:37:39
【问题描述】:

所以我试图在我的每个循环中获取一个索引。这可能吗。这是我的代码:

@each $food, $tons-produced in $top-foods {
  $i: index($top-foods, $food);
  rect:nth-child(#{$i + 1}){

  }
}

返回“无效的空操作:'null 加 1'。”

所以它没有索引并且 $i 为空。

我也试过$i: index($top-foods, ($food, tons-produced));

这是我正在浏览的清单:

$top-foods: ("Sugar Cane" 1898),
("Corn" 1017),
("Rice" 738),
("Wheat" 711),
("Cow Milk" 635),
("Potatoes" 374),
("Vegetables" 279),
("Soy Beans" 278),
("Cassava" 263),
("Sugar Beets" 247);

【问题讨论】:

    标签: sass


    【解决方案1】:

    我不确定我是否理解你,这是你想少花钱多办事吗?:

    @for $i from 1 through length($top-foods){
      selector:nth-child(#{$i}){
        display:block;
      }
    }
    

    http://www.sassmeister.com/gist/fc9cf973e81c80c496e3d6111e62bce5

    更新

    我无法在@each 循环中获得具有多个值的index。尝试使用单个值。而且你不能在nth-child()里面做加法,先做吧。

    @each $food in $top-foods {
      $i: index($top-foods, $food);
      $i: $i + 1;
      rect:nth-child(#{$i}){
        display: block;
      }
    }
    

    http://www.sassmeister.com/gist/c00a1b1577166dbf4a711426604b2f54

    【讨论】:

    • 小心“更新”部分,即使它在这种特殊情况下工作,如果它是一个简单的列表并包含两个相似的值 ex(value1, value2, value2 ...),这会导致问题!据我所知,重复值的索引将被跳过。
    【解决方案2】:

    这是我对这个问题的看法。

    $vals : (
      (32px, $red, 8%, 90%)
      (18px, $red, 18%, 46%)
      (48px, $yellow, 25%, 97%)
      (40px, $red, 26%, 30%)
    );
    
    @for $i from 1 through length($vals) {
        $val : nth($vals, $i); // <-- store the current item in a variable
        .items .nth-#{$i} {
            width: #{nth($val, 1)}; // <-- reference item's values
            height: #{nth($val, 1)};
            background-color: #{nth($val, 2)};
            left: #{nth($val, 3)};
            top: #{nth($val, 4)};
        }
    }
    

    这对我来说效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 2021-07-26
      • 2015-06-01
      • 2015-06-13
      • 2015-03-30
      • 2017-12-05
      • 2011-06-14
      • 2014-08-03
      相关资源
      最近更新 更多