2014-09-01 103 views
1

我有一个按钮类,设置了填充等对元件,随后定义背景颜色的类。LESS使用类名称声明变量?

.button { 
    padding: 0.5em 1em; 
    text-transform: uppercase; 
    color: #fff; 
    &.green { 
     background:@green; //declared previously 
    } 
    // ... more colours 
} 

是否可以声明@green变量作为类名?这将节省我不得不复制/粘贴我想要使用的每种颜色的&.green块。

我已经无法找到任何关于这种选择的文档,但东西沿着线:

&.(green|blue|red) { 
    background: @{$1}; 
} 

这将产生如下:

.button.green{background:#00ff00;} 
.button.blue{background:#0000ff;} 
.button.red{background:#ff0000;} 
+0

是,变量可以被用来生成类的名字,如'@ {VAR} {...}'(选择插值)。但对于你的情况,我认为你还需要一个循环来为每种颜色创建一个类。 – Harry 2014-09-01 10:20:09

+0

这将如何完成? – 2014-09-01 10:29:06

+0

一个非常基本的例子是,例如[此](http://codepen.io/hari_shanx/pen/kEzws)。 – Harry 2014-09-01 10:34:10

回答

2

你可以通过使用具有所需颜色列表的变量来实现这一点,创建所需规则和选择器插值的循环如下所示。

@colors: "green","blue","orange","red","yellow"; // the list of colors required 
button { 
    padding: 0.5em 1em; 
    text-transform: uppercase; 
    .loop-colors(@index) when (@index > 0){ // loop to generate rules for each color 
     .loop-colors(@index - 1); // call for the next iteration 
     @color: e(extract(@colors, @index)); // pick the color value from the list one by one based on current index 
     &[email protected]{color} { 
      background:@color; 
     } 
    } 
    .loop-colors(length(@colors)); 
} 

Codepen Demo

注:正如评论所说,LESS PHP是相当陈旧,因此一些通过以下(相对于环)提供的新功能不被它的支持。这可以通过在this answer中提到的解决方法来解决。

你也可以采取类似的seven-phases-maxthis answer(第二个选项)中提到的一个办法。没有使用循环,该效果可以达到类似的效果。

+1

我有我的颜色变量,所以我改变了'background:@color;'到'background:@@ color;'。 LESS PHP(显然)不支持长度,所以我不得不改变@colours中元素的数量:'.loop-colors(5);' – 2014-09-01 11:18:33