【问题标题】:SASS | @for and @each loop printing values from a list issues萨斯 | @for 和 @each 循环打印列表问题中的值
【发布时间】:2017-12-13 13:46:07
【问题描述】:

我使用sass 来打印带有@each 和@for 循环的列表中的值,但是当我尝试一个一个打印并编译css 中收集的值时,它会将所有值该列表甚至使用nth('', $n) 函数。 我正在使用以下codegulp 作为我的任务运行器。

// SASS CODE
$btn-default: darken(#DDD, 5%);
$btn-alert: red;
$btn-class: "btn-default", "btn-alert";
$btn-color: $btn-default, $btn-alert;

@each $btn in $btn-class {
    .#{unquote($btn)} {
        @for $i from 1 through length($btn-color) {
            background-color: nth($btn-color, $i);
        }
    }
}


/* CSS CODE : OUTPUT */
.btn-default {
  background-color: #d0d0d0;
  background-color: red; }

.btn-alert {
  background-color: #d0d0d0;
  background-color: red; }

我有点卡在一个项目中,我在 sass 中以不同的方式尝试过,当我没有得到值时,它只会返回一个错误。

【问题讨论】:

    标签: css sass gulp


    【解决方案1】:

    不要引入一个内部的@for循环,这将不可避免地在每个规则集中呈现两个属性,而是尝试使用单个循环:

    @for $i from 1 through length($btn-class) {
      #{nth($btn-class, $i)} {
        background-color: nth($btn-color, $i)
      }
    }
    

    不过,从长远来看,我会建议改用地图。这样您就可以在类名和颜色之间建立清晰的关联,从而避免在更大的元素列表中出现潜在错误:

    $buttons: (
      btn-default: $btn-default,
      btn-alert: $btn-alert
    );
    
    @each $class, $color in $buttons {
      .#{$class} {
        background-color: $color;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多