2014-09-01 204 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