在 mixin 中使用守卫

Using guards in the mixin

我想为 Bootstrap 个源创建一个巧妙的混合(mixin->buttons.less)。

我的情况如下:

减去:

.button-variant(@color; @background; @border) {
  color: @color;
  background-color: @background;
  border-color: @border;

  /* this variables must be used when I have parent's  class="invert"*/
  color: @background;
  background: @color;
  border-color: @background;
  /* end */

  /*when not - use variables in the beggining of mixin */

}

我如何看待使用这个 mixin

.btn-primary,
.btn-primary-invert{
    .button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
}

我可以做我想做的事情吗?我知道可以用 Less guards 来完成,但不知道如何使用它。有人有什么想法吗?

最简单的方法是像下面的代码片段一样使用父选择器 (&) 而忘记使用守卫。这里 mixin 默认为所有按钮生成正常和反转状态。如果您希望两种状态都适用于所有按钮,则可以使用它。

.button-variant(@color; @background; @border) {
  &{
    &:hover, &:active{
      color: @color;
      background-color: @background;
      border-color: @border;
    }
  }
  &-invert{
    &:hover, &:active{
      color: @background;
      background: @color;
      border-color: @background;
    }
  }
}

.button-primary{
  .button-variant(#000; #fff; #777);
}

上面的代码片段在编译后会产生以下结果 CSS:

.button-primary:hover,
.button-primary:active {
  color: #000000;
  background-color: #ffffff;
  border-color: #777777;
}
.button-primary-invert:hover,
.button-primary-invert:active {
  color: #ffffff;
  background: #000000;
  border-color: #ffffff;
}

如果你真的想为任何偏好使用守卫(比如你不想要特定按钮的任何一种状态),那么你可以使用如下代码片段。使用守卫,你需要发送一个额外的参数来指示可以验证守卫的类型。

.button-variant(@color; @background; @border; @type:normal) {
  & when (@type = normal){
    color: @color;
    background-color: @background;
    border-color: @border;
  }
  & when (@type = invert){
    color: @background;
    background: @color;
    border-color: @background;
  }
}

.button-primary{
  .button-variant(#000; #fff; #777);
}
.button-primary-invert{
  .button-variant(#000; #fff; #777; invert);
}