您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用LESS构建选择器列表

使用LESS构建选择器列表

如前所述,您的尝试几乎就在那里,由于可见性规则可变,因此无法正常工作。请注意,每次.selector-list迭代都定义了新@selector- list变量,该变量在当前作用域中具有更高的优先级,但不会覆盖@selector-list外部作用域(即先前.selector-list迭代及以上 迭代的作用域)中的变量。因此,当您@selector-list在首次.selector-list调用后使用时,您将获得“最高”.selector-list迭代中设置的值 (即第一个带有的值@i = 1)。

“重返”从递归循环的最后一次迭代的值,你需要使用此值定义一个变量 内的最后一次迭代。通常,最简单的方法是提供“终端” mixin(即,递归mixin的最后一次调用的特殊化)。实际上,无论如何,您都将需要这样的终端来处理列表的最终逗号。例如:

.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;
}

与上述相同,只是稍微“优化”:

.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;
}

一般而言,在Less上下文中,“基于字符串的选择器操作”并不总是一个好主意。主要的问题是少不把这样的字符串为“原生”选择和最先进的减配也不会与他们合作(如少也不会承认,&和类似的元素有那么这样的规则不能嵌套,extend也无法看到此类选择器等。)。另一种“较少友好”的方法是将这样的列表定义为混合而不是变量,例如:

.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;
});

等等

PS另外,更笼统地说,请不要错过更少的媒体查询,可以将其放入选择器规则集中,因此,根据用例,编写一次选择器列表并设置依赖于媒体的样式通常也更容易在内部(例如,与标准CSS方法相反,您必须为每个媒体查询重复相同的选择器)。

其他 2022/1/1 18:13:32 有845人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶