根据LESS中的索引更改间隔

时间:2014-11-27 14:47:02

标签: less

我想更改在LESS循环内计算值的因子。

现在我的代码是

@names:
    1q, 
    half, 
    3q,
    one,
    two,
    three,
    four,
    five,
    six,
    seven,
    eight;

.margin(8);

.margin(@n, @i: 1) when (@i =< 4) {
  @name: extract(@names, @i);
  .space-@{name}, .space-@{name}-top { margin-top: @i * 0.25rem !important; }
  .space-@{name}, .space-@{name}-bottom { margin-top: @i * 0.25rem !important; }
  .margin(@n, (@i + 1));
}

产生:

.space-1q,
.space-1q-top {
  margin-top: 0.25rem !important;
}
.space-1q,
.space-1q-bottom {
  margin-top: 0.25rem !important;
}
.space-half,
.space-half-top {
  margin-top: 0.5rem !important;
}
.space-half,
.space-half-bottom {
  margin-top: 0.5rem !important;
}
.space-3q,
.space-3q-top {
  margin-top: 0.75rem !important;
}
.space-3q,
.space-3q-bottom {
  margin-top: 0.75rem !important;
}
.space-one,
.space-one-top {
  margin-top: 1rem !important;
}
.space-one,
.space-one-bottom {
  margin-top: 1rem !important;
}

我希望从第5次迭代开始,就像.space-@{name}, .space-@{name}-top { margin-top: @i * 1rem !important; }而不是0.25

是否可以在循环中包含另一个when?或者我应该使用另一个功能?

1 个答案:

答案 0 :(得分:1)

  

是否可以在循环中包含另一个when

是的,它是(对嵌套mixins /规则集没有限制,每个都可以有一个防护)。 但是在这种情况下,直接在数组本身中提供这些值而不是特定索引的硬编码会减少膨胀和更一致:

@numb3rs:
    1q   1/4,
    half 1/2,
    3q   3/4,
    one   1,
    two   2,
    three 3,
    four  4,
    five  5,
    six   6,
    seven 7,
    eight 8;

.margin();
.margin(@i: length(@numb3rs)) when (@i > 0) {
    .margin(@i - 1);
    @item: extract(@numb3rs, @i);
    @key:  extract(@item, 1);
    .space-@{key} {
        margin: 1rem * extract(@item, 2);
    }
}

甚至可以完全摆脱循环:

.numb3rs() {
    .-(1q,   1/4);
    .-(half, 1/2);
    .-(3q,   3/4);
    .-(one,   1);
    .-(two,   2);
    .-(three, 3);
    .-(four,  4);
    .-(five,  5);
    .-(six,   6);
    .-(seven, 7);
    .-(eight, 8);
}

.margin();
.margin() {
    .numb3rs();
    .-(@key, @value) {
        .space-@{key} {
            margin: 1rem * @value;
        }
    }
}