如何仅对 less 中的几个变量之一使用默认变量

How to use the default variable for only one of a few variables in less

这是我的 mixin

.test(@color:black; @width:100px; @height:50px) {
    width:@width; 
    height:@height; 
    background:@color;
    }

这里是后面调用​​的地方

 .mydiv {.test('use-mixin-color'; 300px; 150px);}

如何在使用 mixin 中定义的颜色的同时覆盖 .mydiv 的大小? 我尝试过的一切都会覆盖混合颜色。

要在 LESS 中使用 mixin,请传递这些参数以覆盖 mixin 默认值:

解决方案:

.test(@color:black; @width:100px; @height:50px) {
    width : @width; 
    height : @height; 
    background : @color;
 }

.mydiv {
    .test(@width : 300px; @height : 150px);
 }

输出:

 .mydiv {
   width: 300px;
   height: 150px;
   background: black;
 }

有帮助:)

除了已接受的答案。有多种方法(实际上是无限的),但如果您希望您的混合最容易使用,您可以为特定参数值或参数数量提供"specialization"。例如:

// usage:

.foo {.test(red, 1px, 2px)}
.bar {.test(3px, 4px)}

// impl.:

.test(@color, @width, @height) {
    width: @width; 
    height: @height; 
    background: @color;
}

.test(@width, @height) { // <- "no color" specialization
    .test(black, @width, @height);
}

Demo.


在为 mixin 添加默认参数值之前也要三思:

.test(@color: black, @width: 100px, @height: 50px) { ...

人们往往会过度使用此功能,而除了一些特定的用例之外,它很少真正需要(并且只会产生额外的代码噪音)。 IE。考虑一下你是否真的希望你的 mixin 被调用为:

test;
test(blue, 4em);
// etc.

你呢? 在没有默认参数值的情况下开始通常是个好主意(至少是为了保护 mixin 免受意外误用),即:

.test(@color, @width, @height) { ...

稍后添加它们在需要的地方和时间。