减少变量:如何选择几组颜色中的一种?

时间:2014-02-20 19:58:39

标签: less

我想定义多组品牌颜色,并在构建时只选择其中一种(使用Grunt)。

例如(伪代码):

@brand: null;

if @brand = brand1 {
  @colour1: red;
  @colour2: blue;
  @colour3: green;

  @globalTextColor: @colour1
  @bodyBackgroundColor: @colour2
  @linkTextColor: @colour3
  @linkTextHoverColor: @colour1

} 

if @brand = brand2 {
  @colour1: orange;
  @colour2: black;

  @globalTextColor: @colour1
  @bodyBackgroundColor: @colour2
  @linkTextColor: @colour1
  @linkTextHoverColor: @colour1
}

otherwise {
  @colour1: pink;
  @colour2: purple;
  @colour3: cyan;
  @colour4: white;

  @globalTextColor: @colour1
  @bodyBackgroundColor: @colour2
  @linkTextColor: @colour3
  @linkTextHoverColor: @colour4
}

body {
  background: @bodyBackgroundColor;
  color: @globalTextColor;
}
a {
  color: @linkTextColor;
}
a:hover {
  color: @linkTextHoverColor;
}

然后在Grunt中设置@brand变量,然后再运行less build。

我真的很难找到用Less做这个的方法,(但在Sass看来相当简单)。

1 个答案:

答案 0 :(得分:2)

使用pattern matching,如下所示:

@brand: null;
.setColors(@brand); //call setter mixin

.setColors(null) { //default
  @colour1: pink;
  @colour2: purple;
  @colour3: cyan;
  @colour4: white;

  @globalTextColor: @colour1;
  @bodyBackgroundColor: @colour2;
  @linkTextColor: @colour3;
  @linkTextHoverColor: @colour4;
}

.setColors(brand1) { 
  @colour1: red;
  @colour2: blue;
  @colour3: green;

  @globalTextColor: @colour1;
  @bodyBackgroundColor: @colour2;
  @linkTextColor: @colour3;
  @linkTextHoverColor: @colour1;    
} 

.setColors(brand2) {
  @colour1: orange;
  @colour2: black;

  @globalTextColor: @colour1;
  @bodyBackgroundColor: @colour2;
  @linkTextColor: @colour1;
  @linkTextHoverColor: @colour1;
}

此外,在您发布的原始代码中,您在部分颜色设置后省略了分号,因此您需要使用分号才能解析它。

说明

当您设置@brand变量时,将在.setColors(@brand); mixin调用中使用该变量,然后该变量会查找与变量设置的“模式”“匹配”,如果找到,输出那些颜色变量供使用。如果找不到,您将收到No matching definition was found for的编译错误,其格式不匹配,这将告诉您尚未定义“品牌”设置。