正如已经提到的,您的尝试即将完成,但由于可变可见性规则,它不起作用。
请注意,每个.selector-list
迭代定义新的@selector-list
在当前范围内具有更高优先级但不会覆盖的变量@selector-list
外部作用域的变量(即前面的作用域).selector-list
迭代和above)。所以当你使用@selector-list
在最初的之后.selector-list
调用你获取“最高”中设置的值.selector-list
迭代(即第一个迭代@i = 1
).
要“返回”递归循环的最后一次迭代的值,您需要使用该值定义一个变量only在最后一次迭代中。通常,最简单的方法是提供一个“终端”mixin(即递归mixin的最后一次调用的专门化)。事实上,无论如何,您都需要这样的终端来处理列表的最后一个逗号。例如。:
#1
.selector-list(@parent, @children, @i: 1, @list: "") when (@i < length(@children)) {
@child: extract(@children, @i);
.selector-list(@parent, @children, (@i + 1), "@{list} @{parent} @{child},");
}
.selector-list(@parent, @children, @i, @list) when (@i = length(@children)) {
@child: extract(@children, @i);
@selector-list: e("@{list} @{parent} @{child}");
}
// usage:
@text-elements: p, ul, ol, table;
.selector-list("body.single .entry-content", @text-elements);
@{selector-list} {
line-height: 1.8;
}
-
#2与上面相同,只是稍微“优化”:
.selector-list(@parent, @children, @i: length(@children), @list...) when (@i > 1) {
.selector-list(@parent, @children, (@i - 1),
e(", @{parent}") extract(@children, @i) @list);
}
.selector-list(@parent, @children, 1, @list) {
@selector-list: e(@parent) extract(@children, 1) @list;
}
// usage:
@text-elements: p, ul, ol, table;
.selector-list("body.single .entry-content", @text-elements);
@{selector-list} {
line-height: 1.9;
}
-
#3说到一般用例,“基于字符串的选择器操作”在 Less 上下文中并不总是一个好主意。主要问题是 Less 不会将此类字符串视为“本机”选择器,并且大多数高级 Less 功能无法与它们一起使用(例如,Less 无法识别,
, &
和类似的元素,所以这样的规则不能嵌套,extend
也看不到这样的选择器等)。
另一种更“不太友好”的方法是将此类列表定义为 mixin 而不是变量,例如:
.text-elements(@-) {p, ul, ol, table {@-();}}
body.single .entry-content {
.text-elements({
line-height: 1.8;
});
}
并且(当你还需要重用时body.single .entry-content /.text-elements/
):
.text-elements(@-) {
p, ul, ol, table
{@-();}}
.selector-list(@-) {
body.single .entry-content {
.text-elements(@-);
}
}
.selector-list({
line-height: 1.9;
});
etc.
-
附:另外,更一般地说,不要错过在 Less 中媒体查询可能会放入选择器规则集中,因此根据用例,一次编写选择器列表并在其中设置媒体相关样式通常也更容易(即,与标准 CSS 方法相反,您必须为每个媒体查询重复相同的选择器)。