更少的CSS - 访问类名的一部分并在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 循环 mixin 作为中间帮助程序,然后调用它指定要生成的类数。以下是如何执行.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)}

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

以下是

正在发生的事情:

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

最新更新