可以通过lesscss中的另一个变量设置参数默认值吗?

时间:2011-07-15 16:57:15

标签: css less

使用lesscss时是否可以通过另一个变量声明默认参数?我已经尝试过,但无法让它发挥作用。它真的可能吗?

此处的目的是将@button_bg_color设置为默认值@button_gradient_from and @button_gradient_to不应声明。

@button_bg_color: #9cc961;
@button_txt_color: #fff;

@darkened_button_bg_color: @button_bg_color - #2b2b2b;

.branded_button(@from_color: @button_bg_color, @to_color: @darkened_button_bg_color) {
  color: @button_txt_color;
  background-color: @from_color;
  /* FireFox 3.6 */
  background-image: -moz-linear-gradient(top, @from_color, @to_color);
  /* Safari4+, Chrome */
  background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0, @from_color),color-stop(1, @to_color));
}

.button {
  a {
    .branded_button(@button_gradient_from, @button_gradient_to);
  }
}

++++++++++++++++++++++++++++++++++++++++++

编辑:根据此类似帖子更改为混音:are variable mixin names in LESS possible?但是这会因以下渲染而失败:

.branded_button(@from_color: @button_bg_color {
  color:#ffffff;
  background-color:;
  background-image:-moz-linear-gradient(top,,);
  background-image:-webkit-gradient(linear,left bottom,left top,color-stop(0,),color-stop(1,));
}

1 个答案:

答案 0 :(得分:1)

您可以在本地范围内重新定义全局变量。 Mixin将使用新值调用。在局部范围之外,全局变量将保留其值。请参阅此LESS代码。

/* global variables */
@f-border-width: 4px;
@f-border-style: solid;
@f-border-color: #BE2;

/* default parameters - global variables */
.f-border (
        @width: @f-border-width, 
        @style: @f-border-style,
        @color: @f-border-color
    ) {
    border: @width @style @color;
}

/* using initial value of global variable "@f-border-color" */
.base-1 {
    .f-border;
}

/* changing global variable "@f-border-color" in the local scope */
.extension {
    @f-border-color: #F16;
    .f-border;
}

/* outside of the local scope of ".extension" */
/* global variable "@f-border-color" preserves its value */
.base-2 {
    .f-border;
}

它将被编译成这个CSS代码。

.base-1 {
  border: 4px solid #bbee22;
}

.extension {
  border: 4px solid #ff1166;
}

.base-2 {
  border: 4px solid #bbee22;
}

请参阅the demo