繁体   English   中英

更少的CSS-访问类名称的一部分并在mixin中使用

[英]Less CSS - access part of class name and use in mixin

在Less中,是否可以访问类名称的一部分并在mixin中使用?

最好用一个例子解释一下:

我有一个网格,我已经声明如下:

.columns (@columns) {
    //code here to generate column widths
}

//This is where my problem is:
.column-1 {
    .col (1)
}
.column-2 {
    .col (2)
}
.column-3 {
    .col (3)
}
// etc etc

显然,这里有很多重复的代码。 理想情况下,我希望不必声明第1列,第2列等,并拥有某种方法(也许是正则表达式)来解析类名,并使用破折号后的值自动计算列宽。 我几乎可以肯定,twitter引导程序正在执行类似的操作,但我无法理解:

.spanX (@index) when (@index > 0) {
      (~".span@{index}") { .span(@index); }
      .spanX(@index - 1);
    }
    .spanX (0) {}

我想您会明白的:

.columnX (@index) when (@index > 0) {          // Guarded mixin: use this mixin when the condition is true (like an if statement)
    (~".column-@{index}") {                    // outputs .column-0 as a class name
        .col(@index);                          // for the contents, use the col mixin
    }    // which class you are doing

    .columnX(@index - 1);                      // Recursive call to the same mixin, going down by 1
}
.columnX (0) {} // Default implementation so that when .columnX(0) is called, a matching mixin is found.

.col (@index) {
    // actual css that will be applied to column-1 if @index is 1
    width: @index * 10px; // for example
}
.columnX(3);                                   // number of columns you want

编辑 (错过了;.columnX(3); 编辑增加了更多的评论

所有这些都将产生结果:

.column-3 {
    width: 30px;
}
.column-2 {
    width: 20px;
}
.column-1 {
    width: 10px;
}

这与@sherbrow的答案基本相同,但更为简洁,不会出错。 考虑这是一个很长的解释性评论,以支持他的正确答案-远远不止于评论!

您将使用像这样的LESS循环混合作为中间帮助程序,然后调用它指定您要生成的类的数量。 这是.column-1.column-2.column-3 如果要说的话,您希望最多增加四列:只需执行.columns(4)而不是.columns(3) [第9行]。 要增加到五列,只需执行.columns(5)

1    // we'll call this if we want to build columns
2    .columns(@i) when (@i > 0) {
3      .column-@{i} {
4        .col(@i)
5      }
6      .columns(@i - 1)
7    }
8    // for example, here we build columns 1-3
9    .columns(3);

这将编译为

.column-1 {.col(1)}
.column-2 {.col(2)}
.column-3 {.col(3)}

(您的问题假设已经有一个mixin .col(@x)所以我也假设这样做。有关如何跳过该额外步骤的信息,请参见4。

这是正在发生的事情:

  1. 整个第一块[第1-7行]都坐在那里直到被调用。
  2. .columns(3) [第9行]将我们发送到.columns(@i) mixin [第2行],将变量@i赋值为3
  3. 因为@i (3)大于0 [第2行],所以我们满足了后卫的要求,并且被允许经过{ [第2行]。
  4. .column-@{i} {...} [第3-5行]是此mixin将输出的内容。
    • @i为3,因此输出为.column-3 {.col(3)}
    • @{i}语法用于将变量的值作为字符串插入
    • 如果您不需要在其他任何地方使用.col(@x) ,也可以直接在此处放置样式,例如(là .column-@{i} {width: @i * 10px} sherbrow) .column-@{i} {width: @i * 10px}
  5. 然后循环 :编译第3-5行后,再次调用此mixin,但使用不同的值[第6行] .columns(@i - 1) .columns(3 - 1) ==> .columns(2) .columns(3 - 1) ==> .columns(2)
  6. 返回顶部[第2行]:@ @i (现在为2)大于零,因此允许输入.column-2 {.col(2)} (其中.col(2)立即编译,因此您编译的CSS实际上读取的是.column-2 { the.col(2)styles }
  7. 并继续输出和循环直到@i不大于0(即在.columns(1)之后停止)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM