如何在存储颜色名称的 Less 变量中转义引号

How to escape quotes in Less variable which stores a color name?

本文关键字:变量 Less 转义 存储 颜色      更新时间:2023-09-26

我正在做一个HTML/CSS项目。我想根据颜色为标签和文本创建类。例如

text-red{
    color: red;
}
label-white{
    color: white;
}

为此,我正在尝试创建一个 mixin,它接受名称和颜色作为参数并创建此类。我写了以下混合:

.mixin(@name, @color) {
    .text-@{name} {
        color: @color !important;
    }
    .label-@{name} {
        color: @color !important;
    }
}
.mixin('white', white);

这给了我以下输出

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

如果我将此混合运行为 .mixin(白色,白色);我得到

.text-#ffffff{
    color: #ffffff
}

如何使用 mixin 创建像文本白色这样的类?

来自 LESS "e" 函数参考:

e(@string); // escape string content

如果您使用该函数e您将获得正确的结果。

.mixin(@name, @color) {
    .text-@{name} {
        color: @color !important;
    }
    .label-@{name} {
        color: @color !important;
    }
}
.mixin(e('white'), white);

您还可以创建一个变量,然后将其用于多种用途:

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

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) );

    .myclass1-@{current_color} {
        color: @current_color;
    }
    .myclass2-@{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();

我希望它会有所帮助...