4

我正在开发一个 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(white, white); 我明白了

.text-#ffffff{
    color: #ffffff
}

如何使用 mixin 创建像 text-white 这样的类?

4

2 回答 2

9

来自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);
于 2013-10-13T20:38:17.410 回答
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) );


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

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

于 2014-06-27T09:35:53.863 回答