从列表动态创建类的函数

时间:2014-09-22 13:52:20

标签: sass

我对SASS很新,我对列表的工作方式感到困惑。我有一个像这样的多维列表:

$stylethemes: {
  (15, bold, red),
  (12, normal, blue)
}

我现在想要一个函数为$ stylethemes中的每个列表创建一个类,然后将该列表的值放入该类中。我想从上面列表中得到的输出是:

.theme1{
   font-size: 15;
   font-weight: bold;
   color: red;
}

.theme2{
   font-size: 12;
   font-weight: normal;
   color: blue;
}

任何人都可以告诉我如何做到这一点吗?提前谢谢。

2 个答案:

答案 0 :(得分:3)

产生所需结果的代码如下所示:

$stylethemes: (
  (15, bold, red),
  (12, normal, blue)
);

@for $i from 1 through length($stylethemes) {
  .theme#{$i} {
    font-size: nth(nth($stylethemes, $i), 1);
    font-weight: nth(nth($stylethemes, $i), 2);
    color: nth(nth($stylethemes, $i), 3);
  }
}

但是,你会发现这不是特别灵活。您最好使用属性/值的映射,这样您就不必保证特定的顺序:

$stylethemes: (
  (font-size: 15, font-weight: bold, color: red),
  (font-size: 12, font-weight: normal, color: blue)
);

@for $i from 1 through length($stylethemes) {
  .theme#{$i} {
    @each $prop, $val in nth($stylethemes, $i) {
      #{$prop}: $val;
    }
  }
}

或者

$stylethemes: (
  theme1: (font-size: 15, font-weight: bold, color: red),
  theme2: (font-size: 12, font-weight: normal, color: blue)
);

@each $theme, $properties in $stylethemes {
  .#{$theme} {
    @each $prop, $val in $properties {
      #{$prop}: $val;
    }
  }
}

答案 1 :(得分:2)

你基本上要求我们解决你的pboelm,但很好,因为SASS使用起来非常深刻和有趣,并且由于缺乏地图循环功能而有点令人生畏。我改变了一些事情,但基本上就是这样:

// first off, I decided to make your style themes a SASS map. This is useful because your
// your theme will be intricately linked to its name, making it easier to read
// you could to the same with the values, but for now I'll count them.
$stylethemes: (
  theme-1 : (15, bold, red),
  theme-2 : (12, normal, blue)
);

// first, we need to create a regular list we can loop through with a for loop
// map-keys returns a list we can use for that
$allthemes : map-keys($stylethemes);

// then we can run through all the themes by finding the theme name from the above list
@for $var from 1 through length($allthemes) {
    // heres how we get the theme name
    $theme : nth($allthemes, $var);
    // heres how we get the values stored in your SASS map
    $this : map-get($stylethemes, $theme);
    // then I assign all your variables to vars, but its not necessary
    $size : nth($this, 1);
    $style : nth($this, 2);
    $color : nth($this, 3);
    // now print the theme name as a classname
    .#{$theme}{
       // then print the values - you could also use the above nth($this, n) to get them.
       font-size: $size;
       font-weight: $style;
       color: $color;
    }
}

我从SASS文档站点获得了所有功能信息:http://sass-lang.com/documentation/Sass/Script/Functions.html,所以看看那里,有一个列表和地图的专用部分。看一下列表和地图,因为它们对于这类事物非常有用。