如何在循环中使用守卫?

时间:2018-04-23 13:25:50

标签: css less

是否可以使用少一个循环来获得所需的结果?

    .loop(2);

    .loop (@n, @j: @n) when (@j >= 0) {
        .loop(@j, @j - 1/2);
        @i: floor(@j);            // integer part
        @f: floor(mod(@j, 1)*10); // fractional part
        .height-@{i}-@{f} {
            height: 1% * @j;
        }
    }

结果:

.height-0-0 {
  height: 0%;
}
.height-0-5 {
  height: 0.5%;
}
.height-1-0 {
  height: 1%;
}

如何获得这样的结果(不要显示第二个0)?

.height-0 {
  height: 0%;
}
.height-0-5 {
  height: 0.5%;
}
.height-1 {
  height: 1%;
}

height-1-5
height-2

e.t.c。

1 个答案:

答案 0 :(得分:2)

你只需要一些守卫(可以用作if语句)在你的循环中,这里是docs

http://lesscss.org/features/#css-guards-feature

这是一支笔https://codepen.io/anon/pen/deGWKR

.loop(2);

.loop (@n, @j: @n) when (@j >= 0) {
  .loop(@j, @j - 1/2);
  @i: floor(@j); // integer part
  @f: floor(mod(@j, 1)*10); // fractional part

  .height-@{i}-@{f} when (@f > 0) {
    height: 1% * @j;
    color: red;
  }

  .height-@{i} when (@f = 0) {
    height: 1% * @j;
    color: brown;
  }
}

这会生成

.height-0 {
  height: 0%;
  color: green;
}
.height-0-5 {
  height: 0.5%;
  color: red;
}
.height-1 {
  height: 1%;
  color: green;
}
.height-1-5 {
  height: 1.5%;
  color: red;
}
.height-2 {
  height: 2%;
  color: green;
}

.height-@{i}-@{f} when (@f > 0) {...}表示仅当f大于0时生成此类

.height-@{i} when (@f = 0) {...}表示仅在f等于0时生成此类