在Less中循环遍历变量名称数组

在我们的应用程序中,我们有一个预设的颜色列表,用户可以从中选择颜色,并且与该用户相关的所有内容都将具有该颜色。


在整个应用程序中,我们将提供带有颜色作为类名称附加的各种模块。


例如。


<div class="example_module green">

  ...

</div>

我们在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是否甚至支持这种功能?


慕婉清6462132
浏览 2275回答 3
3回答

慕盖茨4494581

请参阅循环。例如(假设@green,@red,@blue变量别处定义):@colors: green, red, blue;.example_module {&nbsp; &nbsp; .-(@i: length(@colors)) when (@i > 0) {&nbsp; &nbsp; &nbsp; &nbsp; @name: extract(@colors, @i);&nbsp; &nbsp; &nbsp; &nbsp; &.@{name} {background: @@name}&nbsp; &nbsp; &nbsp; &nbsp; .-((@i - 1));&nbsp; &nbsp; } .-;}---在Modern Less中,借助Lists插件可以更直接:@colors: green, red, blue;.for-each(@name in @colors) {&nbsp; &nbsp; .example_module.@{name} {&nbsp; &nbsp; &nbsp; &nbsp; background: @@name;&nbsp; &nbsp; }}---在Legacy Less中,语法糖可以使用:@import "for";@colors: green, red, blue;.example_module {&nbsp; &nbsp; .for(@colors); .-each(@name) {&nbsp; &nbsp; &nbsp; &nbsp; &.@{name} {background: @@name}&nbsp; &nbsp; }}"for"可以在此处找到导入的代码段(这只是递归的Less循环的包装mixin)(此处和此处都带有示例)。

梵蒂冈之花

这个mixin对我来说很好用。第二个参数是可以访问当前迭代元素(@value)和索引(@i)的代码块。定义mixin:.for(@list, @code) {&nbsp; &nbsp; & {&nbsp; &nbsp; &nbsp; &nbsp; .loop(@i:1) when (@i =< length(@list)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @value: extract(@list, @i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @code();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .loop(@i + 1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; .loop();&nbsp; &nbsp; }}使用:@colors: #1abc9c, #2ecc71, #3498db, #9b59b6;.for(@colors, {&nbsp; &nbsp; .color-@{i} {&nbsp; &nbsp; &nbsp; &nbsp; color: @value;&nbsp; &nbsp; }});结果CSS:.color-1 {&nbsp; color: #1abc9c;}.color-2 {&nbsp; color: #2ecc71;}.color-3 {&nbsp; color: #3498db;}.color-4 {&nbsp; color: #9b59b6;}

隔江千里

使用现代的LESS(> = 3.7),可以使用内置each函数:/* (assuming @clr-green, @clr-red, @clr-blue variables are defined elsewhere) */@colors: {&nbsp; green: @clr-green;&nbsp; red: @clr-red;&nbsp; blue: @clr-blue;}each(@colors, {&nbsp; .example_module.@{key} {&nbsp; &nbsp; background: @value;&nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP