在less中遍历数组元素

5,272 阅读1分钟
原文链接: eastblueokay.github.io

在Less中并没有对数组遍历的原生支持,我们可以通过mixin递归的方式来实现遍历。

1、定义数组元素

@colors: red, green, blue, black;

2、获取数组元素长度

@length: length(@color);

3、数组元素取值

@item: extract(@colors, @index);

4、遍历

@colors: red, green, blue, black;
.for(@data, @i: 1) when(@i =< length(@data)) {
    @item: extract(@data, @i);
    div {
        background: @item;
    }
    .for(@data, (@i + 1));
}
.for(@colors);

以上的less会被编译成以下css:

div {
  background: red;
}
div {
  background: green;
}
div {
  background: blue;
}
div {
  background: black;
}