5

我有以下更少的代码:

.loop (@index) when (@index >= 10) {
  (~".font@{index}") {
    font-size: ~"@{index}px";
  }
  .loop(@index - 1);
} 
.loop (0) {}
.loop (10);

哪个输出:

.font15 {
  font-size: 15px;
}
.font14 {
  font-size: 14px;
}
.font13 {
  font-size: 13px;
}
.font12 {
  font-size: 12px;
}
.font11 {
  font-size: 11px;
}
.font10 {
  font-size: 10px;
}

Less文档的末尾,我有这个类:

.title{
    font-size:14px;
    margin-bottom:0.5em;
    .font13;
}

我正在使用 WinLess 编译它,但我收到一条错误消息,提示“.font13”未定义有没有办法在同一个文档中使用“动态”定义的类?

谢谢!

4

1 回答 1

5

Unfortunately. The selector interpolation is just string interpolation, and the string gets then printed into CSS, so no class object is generated in the Less run.

So the best way to do something like this would be to design a getter mixin (that you can call from other rules) and maybe a generator mixin (that writes the .font10, .font11, ... .fontNN classes) ... the later is not necessary if you want to generate the classes only in the loop (and you can just merge it with the loop).

Something like this:

.getFont(@size) { font-size: ~"@{size}px"}

.genFontClass (@size) {
   (~".font@{size}") { .getFont(@size); }
}

and then you can use your loop to generate the .fontNN classes:

.loop (@index) when (@index >= 10) {
    .genFontClass (@index);
    .loop(@index - 1);
} 
.loop (@index) when (@index < 10) {}

using for example index 13:

.loop (13);

with output CSS:

.font13 {
  font-size: 13px;
}
.font12 {
  font-size: 12px;
}
.font11 {
  font-size: 11px;
}
.font10 {
  font-size: 10px;
}

and independently from this generated classes that got printed directly to the output CSS (and are inaccessible from other Less rules), you can call the getter mixin, to add desired properties to your rules, in our example the font for the desired index 13:

.title{
    margin-bottom:0.5em;
    .getFont(13);
}

which will now add the font size property to the .title rule.

CSS:

.title {
  margin-bottom: 0.5em;
  font-size: 13px;
}

Hope this helps.

于 2013-07-02T11:07:12.557 回答