我会以这种方式去做:
.generateClasses (@index, @n, @in:"") when (@index > 0) {
@concatenate: "@{in} .repeatedClass";
@selector: ~".staticClass @{concatenate} > .finalStaticClass";
@{selector}{ height: unit(@n,px) };
.generateClasses((@index - 1), (unit(@n) + 10), @concatenate);
}
.generateClasses(0, @n, @in){};
.generateClasses(4, 10px);
您将连接生成的类传递到下一个循环,并且每次添加另一个类。@index
是循环的计数器,是@n
您要增加的值。
CSS 输出:
.staticClass .repeatedClass > .finalStaticClass {
height: 10px;
}
.staticClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 20px;
}
.staticClass .repeatedClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 30px;
}
.staticClass .repeatedClass .repeatedClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 40px;
}
编辑 - 对于旧版本的 Less:
在 Less <= 1.3.3 中,您需要将各个连接循环包含在一个单独的角色中(.test
在下面的示例中调用它),以限制变量。然后你可以遍历这个,按照这些思路做一些事情:
.generateClasses (@index, @n, @in:"") when (@index > 0) {
@concatenate: "@{in} .repeatedClass";
@selector: ~".staticClass @{concatenate} > .finalStaticClass";
.generateClasses((@index - 1), (unit(@n) + 10), @concatenate);
}
.generateClasses(0, @n, @in){};
.test(@i, @ni){
.generateClasses(@i,@ni);
@{selector} {
height: @ni;
}
}
.printClasses(@i:1,@ni:10px) when (@i > 0) {
.test(@i,@ni*@i);
.printClasses(@i - 1,@ni);
}
.printClasses(4);
输出 CSS 现在将是:
.staticClass .repeatedClass .repeatedClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 40px;
}
.staticClass .repeatedClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 30px;
}
.staticClass .repeatedClass .repeatedClass > .finalStaticClass {
height: 20px;
}
.staticClass .repeatedClass > .finalStaticClass {
height: 10px;
}
如果您只需要一次生成一个选择器,您可以跳过第二个循环,只需.test()
在需要的地方调用 mixin。