2013-10-13 20 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(); 

我希望这将有助于...

相关问题