在我们的应用程序中,我们有一个预设的颜色列表供用户选择,与该用户相关的所有内容都将具有该颜色.
在整个应用程序中,我们将有各种模块,其颜色附加为类名.
例如.
...
我们在CSS中使用LESS.
在很多地方我们都在做这样的事情:
.example_module.green { background: @green; } .example_module.red { background: @red; } .example_module.blue { background: @blue; } etc
我希望能够将所有这些颜色名称设置为数组并迭代它们.如果我们将来添加颜色,我们只需将它添加到一个地方.
伪代码:
@colors: ['green', 'red', 'blue']; for each @color in @colors { .example_module.@color { background: @color; } }
在LESS中甚至支持这样的东西吗?
请参阅循环.例如(假设@green
,@red
,@blue
变量别处定义):
@colors: green, red, blue;
.example_module {
.-(@i: length(@colors)) when (@i > 0) {
@name: extract(@colors, @i);
&.@{name} {background: @@name}
.-((@i - 1));
} .-;
}
在Modern Less中,在Lists插件的帮助下可以更直接:
@colors: green, red, blue;
.for-each(@name in @colors) {
.example_module.@{name} {
background: @@name;
}
}
在Legacy Less中,可以使用以下方法实现语法糖:
@import "for";
@colors: green, red, blue;
.example_module {
.for(@colors); .-each(@name) {
&.@{name} {background: @@name}
}
}
在这里"for"
可以找到导入的片段(它只是递归Less循环的包装混合)(这里和这里有示例).
这个mixin对我来说很好.第二个参数是一个代码块,可以访问当前迭代元素(@value)和索引(@i).
定义mixin:
.for(@list, @code) { & { .loop(@i:1) when (@i =< length(@list)) { @value: extract(@list, @i); @code(); .loop(@i + 1); } .loop(); } }
使用:
@colors: #1abc9c, #2ecc71, #3498db, #9b59b6; .for(@colors, { .color-@{i} { color: @value; } });
结果css:
.color-1 { color: #1abc9c; } .color-2 { color: #2ecc71; } .color-3 { color: #3498db; } .color-4 { color: #9b59b6; }