sass - SCSS/SASS 列表反向迭代(反向循环)

标签 sass

反转 @for 的顺序SCSS 中的迭代输出可以这样完成:
SCSS 示例:GIST DEMO

$colors : green, gold, red;

a{
  $i : length($colors);
  @each $c in $colors {
      &:nth-child(#{$i}){
           fill:$c;
      }
      $i : $i - 1;
  }
}
输出:
a:nth-child(3) {
  fill: green;
}
a:nth-child(2) {
  fill: gold;
}
a:nth-child(1) {
  fill: red;
}

这是 SASS 反向迭代的最佳方式吗?
有谁知道实现这一目标的更“SCSS 原生”的方式来提高可读性?

最佳答案

你的解决方案没问题。

您可以创建一个函数,该函数将 reverse你的数组:

@function reverse($list, $recursive: false) {
   $result: ();

   @for $i from length($list)*-1 through -1 {
      @if type-of(nth($list, abs($i))) == list and $recursive {
        $result: append($result, reverse(nth($list, abs($i)), $recursive));      
      }

      @else {
        $result: append($result, nth($list, abs($i)));
      }
   }

   @return $result;
}

$list: #aaa, #bbb, #ccc, #ddd;
$new-list: reverse($list);

@for $i from 1 through length($new-list){
  div:nth-child(#{$i}){
    color: nth($new-list, $i);
  }
}

您可以使用 nth-last-child选择器。
@for $i from 1 through length($list){
  div:nth-last-child(#{$i}){
    color: nth($list, $i);
  }
}

你可以重写你的数组:$list: #ddd, #aaa, #bbb, #ccc并使用 nth-child .

关于sass - SCSS/SASS 列表反向迭代(反向循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788991/

相关文章:

javascript - Node.js Sass 版本 7.0.0 与 ^4.0.0 不兼容 || ^5.0.0 || ^6.0.0

css - SCSS/Sass 中的嵌套 CSS3 媒体查询

node.js - grunt-contrib-sass 在 Windows 中不起作用

css - 如何引用 SCSS 兄弟?

html - 如何去除 ionic 4 段指示器(底线)?请告诉我

css - nth-of-type(odd) 不工作 SCSS

Angular:如何动态更改 scss 变量?

sass - 如何像在 React 中那样在 Preact 中简单导入样式?

html - 如何将类定义中的样式应用于除最后一个之外的所有子 div?

sass - Laravel Elixir 不观看 gulp 的 SASS 导入文件