3

我想在项目中对边框使用 Less mixin,但通常我需要使用边框的不同边,而不是全部。

我写了一个简单的mixin:

.border-all (@border; @border-type; @border-color) {
  border-top: @border @border-type @border-color;
  border-right: @border @border-type @border-color;
  border-bottom: @border @border-type @border-color;
  border-left: @border @border-type @border-color;
}

例如,是否可以仅将参数传递给border-topand border-bottom

所以:

.class {
  .border-all (3px; double; @border-color);
}

将输出:

.class {
  border-top: 3px double #333;
  border-bottom: 3px double #333;
}

我可以忽略将参数传递给 mixin 中的不同 CSS 属性吗?

4

2 回答 2

2

事实上,您当前的 mixin 不能被修改为仅将参数发送到特定的 CSS 属性。但是,您可以将 mixin 修改为像下面的代码片段一样,并将边作为参数传递。

.border-all (@border; @border-type; @border-color; @sides...) {
    & when not (@sides = all){ /* if border is not needed on all sides */
        .border-side(@index) when (@index > 0){
            @side: extract(@sides, @index); /* extract the side specified for each iteration */
            border-@{side}: @border @border-type @border-color; /* create property */
            .border-side(@index - 1);
        }
        .border-side(length(@sides)); /* loop as many times as the no. of sides provided */
    }
    & when (@sides = all){ /* if border is needed for all sides */
        border: @border @border-type @border-color; /* combined because there is no need for 4 separate properties. */
    }
}

.demo{
    .border-all(1px; solid; black; top, right);
}
.demo2{
    .border-all(1px; solid; black; all);
}

您只需将所需的边作为最后一个参数传递给 mixin,并且只会在输出 CSS 中生成相应的属性。

于 2015-06-19T08:49:01.187 回答
2

首先我会问你为什么需要那个mixin。怎么比刚才更好border: 3px double @border-color;

同样,我宁愿坚持一个临时变量,而不是为 mixin 制作一个非常臃肿和令人困惑的条件逻辑,例如:

.class {
   @border: 3px double @border-color;
    border-top: @border;
    border-bottom: @border;
}

是的,它是三行代码而不是一行代码,但无疑更容易维护。

---

无论哪种方式,如果我不得不使用这样的 mixin,我可能会将其简化为:

// usage:

.c1 {
    .border(top right, 1px solid black);
}

.c2 {
    .border(1px solid black);
}

// impl:

.border(@sides, @value) {
    .side(length(@sides));
    .side(@i) when (@i > 0) {
        @side: extract(@sides, @i);
        border-@{side}: @value;
        .side(@i - 1);
    }
}

.border(@value) {
    border: @value;
}

因为在这种情况下,我真的看不出使用所有这些多余的逗号和/或分号有任何意义。

于 2015-06-19T10:16:14.570 回答