从列表动态创建类的函数 [英] Function to dynamically create classes from lists
问题描述
我对 SASS 还很陌生,我对列表的工作方式感到困惑.我有一个这样的多维列表:
Im fairly new to SASS and I'm confused by the way lists work. I have a multidimensional list like this:
$stylethemes: {
(15, bold, red),
(12, normal, blue)
}
我现在想要一个函数,它为 $stylethemes 中的每个列表创建一个类,然后将该列表的值放入该类中.我想从上面的列表中得到的输出是这样的:
I now want a function that makes a class for each list in $stylethemes and then puts the values of that list into that class. The output I want from the above list is this:
.theme1{
font-size: 15;
font-weight: bold;
color: red;
}
.theme2{
font-size: 12;
font-weight: normal;
color: blue;
}
谁能告诉我如何做到这一点?提前致谢.
Can anyone show me how I can do this? Thanks in advance.
推荐答案
产生预期结果的代码如下所示:
The code to produce the desired results would look like this:
$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);
}
}
但是,您会发现这不是特别灵活.您最好使用属性/值的映射,这样您就不必保证特定的顺序:
However, you'll find this isn't particularly flexible. You're better off using mappings for the property/values so that you don't have to guarantee a specific order:
$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;
}
}
}
这篇关于从列表动态创建类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!