Javascript 如何在存储颜色名称的较少变量中转义引号?

Javascript 如何在存储颜色名称的较少变量中转义引号?,javascript,html,css,string,less,Javascript,Html,Css,String,Less,我正在做一个HTML/CSS项目。我想根据颜色为标签和文本创建类。比如说 text-red{ color: red; } label-white{ color: white; } 为此,我尝试创建一个mixin,它接受名称和颜色作为参数,并创建这个类。我写了下面的混音: .mixin(@name, @color) { .text-@{name} { color: @color !important; } .label-@{name} {

我正在做一个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(白色,白色)运行此mixin;我明白了

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

来自:

如果您使用函数
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();

如果你这样做,我希望它能帮助…

。你最好使用内联样式。我理解。我会考虑各种可能性。谢谢你指向这些帖子。太好了!它很有魅力。我还尝试将它与~'white'一起使用,这也很有效。是的,这几乎是一样的:)如果我没记错的话,唯一的区别是
~
也对它求值(例如使用变量),而
e
不求值任何东西,只是按原样返回字符串。
@whiteLiteral: e('white');
//mixin declaration code
.mixin(@whiteLiteral, white);
.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();