【问题标题】:SASS/SCSS object key value loop [duplicate]SASS/SCSS 对象键值循环 [重复]
【发布时间】:2013-04-11 14:06:37
【问题描述】:

看看这个例子:

@include font-face('Entypo', font-files('entypo.woff'));

.icon {
  display: inline;
  font: 400 40px/40px Entypo;
}

.icon-star {
  @extend .icon;

  &:after {
    content: "\2605";
  }
}

.icon-lightning {
  @extend .icon;

  &:after {
    content: "\26A1";
  }
}

我想让事情尽可能干燥,所以我想知道以下是否可行,如果可以,如何?

@include font-face('Entypo', font-files('entypo.woff'));

.icon {
  display: inline;
  font: 400 40px/40px Entypo;
}

$icons {
  $star: "\2605";
  $lightning: "\26A1";
}

@each $icon in $icons {
  $key = $icon{key}; // ???
  $value = $icon{value}; // ???

  .icon-#{$key} {
    @extend .icon;

    &:after {
      content: $value;
    }
  }
}

【问题讨论】:

    标签: css loops sass compass-sass


    【解决方案1】:

    Sass 3.3(2014/03/07 发布)现在允许您使用地图:

    @include font-face('Entypo', font-files('entypo.woff'));
    
    .icon {
      display: inline;
      font: 400 40px/40px Entypo;
    }
    
    $icons: (
      star: "\2605",
      lightning: "\26A1"
    );
    
    @each $key, $value in $icons {
      .icon-#{$key} {
        @extend .icon;
    
        &:after {
          content: $value;
        }
      }
    }
    

    【讨论】:

    • 这应该是目前公认的答案。由于接受的答案已过时,我们是否有更新或审查接受的答案的好方法?
    • 您可以更新答案以突出显示它,如果他愿意,操作员仍然可以更改接受的答案。
    • 这应该是最好的答案!
    【解决方案2】:

    Sass 目前不支持映射。你现在必须忍受列表的列表。

    $icons: star "\2605", lightning "\26A1";
    
    @each $icon in $icons {
      $key: nth($icon, 1);
      $value: nth($icon, 2);
    
      .icon-#{$key} {
        @extend .icon;
    
        &:after {
          content: $value;
        }
      }
    }
    

    【讨论】:

    • 我讨厌SASS的文档,为什么我找不到这样一个简单的循环,谢谢,非常感谢。
    • 如果你想要更多程序化的东西,请查看learnboost.github.io/stylus
    • 我在整个网络上遇到的所有其他解决方案之后的最佳答案
    猜你喜欢
    • 2015-10-14
    • 2016-10-06
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2016-03-14
    • 2016-06-22
    相关资源
    最近更新 更多