我有以下更少的代码:
.loop (@index) when (@index >= 10) {
(~".font@{index}") {
font-size: ~"@{index}px";
}
.loop(@index - 1);
}
.loop (0) {}
.loop (10);
哪个输出:
.font15 {
font-size: 15px;
}
.font14 {
font-size: 14px;
}
.font13 {
font-size: 13px;
}
.font12 {
font-size: 12px;
}
.font11 {
font-size: 11px;
}
.font10 {
font-size: 10px;
}
在 Less 文档的末尾我有这个类:
.title{
font-size:14px;
margin-bottom:0.5em;
.font13;
}
我正在使用 WinLess 编译它,但我收到一条错误消息,指出“.font13”未定义 有什么方法可以在同一文档中使用“动态”定义的类吗?
谢谢!
最佳答案
不幸的是。选择器插值只是字符串插值,然后将字符串打印到 CSS 中,因此在 Less 运行中不会生成类对象。
所以做这样的事情最好的方法是设计一个getter mixin(你可以从其他规则调用)和一个生成器mixin(写.font10
, .font11
, ... .fontNN
classes) ...如果你只想在循环中生成类,则后者不是必需的(并且你可以将它与循环合并)。
像这样:
.getFont(@size) { font-size: ~"@{size}px"}
.genFontClass (@size) {
(~".font@{size}") { .getFont(@size); }
}
然后您可以使用循环生成 .fontNN
类:
.loop (@index) when (@index >= 10) {
.genFontClass (@index);
.loop(@index - 1);
}
.loop (@index) when (@index < 10) {}
使用例如索引 13:
.loop (13);
输出 CSS:
.font13 {
font-size: 13px;
}
.font12 {
font-size: 12px;
}
.font11 {
font-size: 11px;
}
.font10 {
font-size: 10px;
}
并且独立于直接打印到输出 CSS 的生成类(并且无法从其他 Less 规则访问),您可以调用 getter mixin,将所需的属性添加到您的规则中,在我们的示例中为所需的字体索引 13:
.title{
margin-bottom:0.5em;
.getFont(13);
}
现在会将字体大小属性添加到 .title
规则。
CSS:
.title {
margin-bottom: 0.5em;
font-size: 13px;
}
希望这对您有所帮助。
关于css - Less - 使用在 protected 混合中创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422158/