如何优化我的LESS mixin?

时间:2014-12-20 03:59:53

标签: twitter-bootstrap less less-mixins

这个mixin为Bootstrap生成帮助类。

我确信有办法使用循环改进这个mixin。

.generate-margin-tops(@size) {
  .mt-@{size}-5 {
    margin-top: 5px;
  }

  .mt-@{size}-10 {
    margin-top: 10px;
  }

  .mt-@{size}-20 {
    margin-top: 20px;
  }

  .mt-@{size}-30 {
    margin-top: 30px;
  }

  .mt-@{size}-40 {
    margin-top: 40px;
  }
}

使用不同屏幕尺寸的代码段:

.generate-margin-tops(xs);

@media (min-width: @screen-sm-min) {
  .generate-margin-tops(sm);
}

@media (min-width: @screen-md-min) {
  .generate-margin-tops(md);
}

@media (min-width: @screen-lg-min) {
  .generate-margin-tops(lg);
}

P.S。查看我的最终solution

2 个答案:

答案 0 :(得分:1)

这可以使用如下的循环进行简化(注释中的内联说明):

.generate-margin-tops(@size, @index) when (@index > 0) {
    @margin-top: extract(@margin-px, @index); //extract the margin value corresponding to the index/counter variable
    .mt-@{size}-@{margin-top} { //selector interpolation to form the selector
        margin-top: unit(@margin-top,px); //converts plain number to px units
    }
    .generate-margin-tops(@size, @index - 1); //call to the next iteration by decrementing the counter
}

@margin-px: 5, 10, 20, 30, 40; //array list variable which contains the various margin pixels

.generate-margin-tops(xs, length(@margin-px)); //call to loop mixin

@media (min-width: @screen-sm-min) {
  .generate-margin-tops(sm, length(@margin-px));
}

@media (min-width: @screen-md-min) {
  .generate-margin-tops(md, length(@margin-px));
}

@media (min-width: @screen-lg-min) {
  .generate-margin-tops(lg, length(@margin-px));
}

答案 1 :(得分:1)

@Harry极大地帮助我处理了较少的周期。最终我找到了这个解决方案:

@margin-tops: quarter 0.25, half 0.5, one 1, two 2, three 3, four 4;

.generate-margin-tops(@suffix: ~'', @i: 1) when (@i =< length(@margin-tops)) {
  @item:  extract(@margin-tops, @i);
  @key:   extract(@item, 1);
  @value: extract(@item, 2);

  .mt-@{key}@{suffix} {
    margin-top: @line-height-computed * @value;
  }

  .generate-margin-tops(@suffix, @i + 1);
}

.generate-margin-tops(-sm)的结果是:

.mt-quarter-sm { margin-top: 5px }
.mt-half-sm { margin-top: 10px }
.mt-one-sm { margin-top: 20px }
.mt-two-sm { margin-top: 40px }
.mt-three-sm { margin-top: 60px }
.mt-four-sm { margin-top: 80px }