2013-10-13 21 views
4

我正在處理HTML/CSS項目。我想根據顏色爲標籤和文本創建類。例如如何在存儲顏色名稱的Less變量中避開引號?

text-red{ 
    color: red; 
} 

label-white{ 
    color: white; 
} 

要做到這一點,我想創建一個接受名稱和顏色作爲參數的mixin並創建這個類。我寫了下面的mixin:

.mixin(@name, @color) { 
    [email protected]{name} { 
     color: @color !important; 
    } 
    [email protected]{name} { 
     color: @color !important; 
    } 
} 

.mixin('white', white); 

這給了我下面的輸出

.text-'white'{ /* notice the quotes*/ 
    color: #ffffff 
} 

如果我運行這個混入作爲.mixin(白,白);我得到

.text-#ffffff{ 
    color: #ffffff 
} 

如何使用mixin創建類似文本的類?

+2

如果你這樣做[你會有一個不好的時間](http://stackoverflow.com/questions/3687763/replacing-css-classes-with-more-generic-ones/3687819#3687819)。你也可以使用內聯樣式。 –

+0

我明白了。我會考慮可能性。感謝您指出帖子。 – suparngp

回答

9

LESS "e" function reference

e(@string); // escape string content 

如果使用e你會得到正確的結果的功能。

.mixin(@name, @color) { 
    [email protected]{name} { 
     color: @color !important; 
    } 
    [email protected]{name} { 
     color: @color !important; 
    } 
} 

.mixin(e('white'), white); 

您還可以創建一個變量,然後將它用於多種用途:

@whiteLiteral: e('white'); 
//mixin declaration code 
.mixin(@whiteLiteral, white); 
+0

太棒了!它像魅力一樣工作。我也嘗試使用〜'白色',這也起作用。 – suparngp

+1

是的,它幾乎是一樣的東西:) –

+0

如果我沒有記錯的話,唯一的區別是''也評估它(例如用變量),而'e'不計算任何東西,只是返回字符串爲-is。 –

1

LightStyle是正確的,但如果你有很多命名顏色設置,你可以使用一個遞歸循環像這樣的串色的列表:

.recursive-loop(@list_size, @list) when (@list_size > 0) { 

    // Get the current color from the list @list at index @list_size 
    @current_color: e(extract(@list, @list_size)); 


    [email protected]{current_color} { 
     color: @current_color; 
    } 

    [email protected]{current_color} { 
     background-color: @current_color; 
    } 

    //etc... 

    // until the end of list 
    .recursive-loop((@list_size - 1), @list) 
} 

.mixin-color(){ 

    // Add color you need to this list and get size of it. 
    @list: "black", "dimgrey", "grey", "lightgrey", "white", "red", "blue", "green"; 
    @list_size: length(@list); 

    // Call recursive loop with the preview list 
    .recursive-loop(@list_size, @list); 

} 

// mixin call 
.mixin-color(); 

我希望這將有助於...

相關問題