7

在这里掌握LESS,但有一件事仍然有点不清楚。

假设我的网站有多个颜色主题,由 body 标签上的类控制。由此我可以为每个主题中的每个元素重新定义各种颜色。如果我有很多元素要改变……和很多主题,这很容易但相当耗时。每次我添加一个新主题时,我都需要用不同的颜色值再次写出所有选择器。

到目前为止,我的工作基于我发现的另一篇文章: LESS.css variable based on class

...但是,对于我想做的事情来说,这似乎仍然过于复杂,因为我仍然必须写出所有选择器并包含 mixin,然后再放入具有颜色变量的相同 CSS。

我在这里创建了一个CODEPEN

如果有人有时间看一看并建议我如何以不同的方式处理此问题或如何简化此过程,我将不胜感激。

非常感谢任何提供帮助的人:)

4

1 回答 1

19

假设您仍然希望在一个样式表中对其进行主题化(而不是像注释中提到的 cimmanon 那样的多个表),并且假设您使用的是 LESS 1.3.2+,那么下面的代码可以通过设置来减少重复量循环遍历需要更改主题的类。

请注意,这在 Codepen 上不起作用(它会抛出错误uncaught throw #,可能是因为它们正在运行早期版本的 LESS),但您可以通过将代码放入LESS 的编译器中看到它正确编译

LESS(基于您的 Codepen 代码,并添加了演示主题)

//////////////////////////////////////////////////////
// CONSTANTS

@lightColour: #fff;
@darkColour: #000;
@lightBg: #fff;
@darkBg: #000;
@numberOfThemes: 3; //controls theme loop

//////////////////////////////////////////////////////
// MIXINS

//Theme Definitions by parametric mixin numbers (1), (2), etc.
.themeDefs(1) {
  @lightColour: #f00;
  @darkColour: #fff;
  @lightBg: #f00;
  @darkBg: #fff;
}

.themeDefs(2) {
  //inverse of 1
  @lightColour: #fff;
  @darkColour: #f00;
  @lightBg: #fff;
  @darkBg: #f00;
}

.themeDefs(3) {
  @lightColour: #cfc;
  @darkColour: #363;
  @lightBg: #cfc;
  @darkBg: #363;
}


.curvy {
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

//////////////////////////////////////////////////////
// GENERAL STYLING

* {padding: 0;margin: 0;}
html {text-align: center;}
h2 {padding: 20px 0;}

.box {
  .curvy;
  color: @lightColour;
  background: @darkBg;
  display:inline-block; width:10%; padding:20px 5%; margin:0 1% 20px 1%;
}

//////////////////////////////////////////////////////
// THEME BUILDING

.buildThemes(@index) when (@index < @numberOfThemes + 1) {

  .theme-@{index} {
      .themeDefs(@index); 
      color: @lightColour;
      background: @darkBg; 

      .box {
        color: @darkColour;
        background: @lightBg;
      }
    }
    .buildThemes(@index + 1);
}
//stop loop
.buildThemes(@index) {}
//start theme building loop
.buildThemes(1);

CSS 输出(为简洁起见,仅显示循环主题 css)

.theme-1 {
  color: #ff0000;
  background: #ffffff;
}
.theme-1 .box {
  color: #ffffff;
  background: #ff0000;
}
.theme-2 {
  color: #ffffff;
  background: #ff0000;
}
.theme-2 .box {
  color: #ff0000;
  background: #ffffff;
}
.theme-3 {
  color: #ccffcc;
  background: #336633;
}
.theme-3 .box {
  color: #336633;
  background: #ccffcc;
}
于 2013-03-07T19:25:58.963 回答