我想以类似于MediaQuery概念的方式使用LESS Guarded Mixins,因此声明一个条件,如果经过验证,则包含一组css规则和声明。
目前,我编写了此示例代码:
.color-theme(@color-type) when (@color-type='cold')
{
color:gren;
}
.color-theme(@color-type) when (@color-type='hot')
{
color:red;
}
text-container
{
.color-theme('hot');
width:960px;
}
我的目的是编写一组类,这些类只有在满足特定条件时才必须使用,其方式与 MediaQuery 逻辑非常相似。 这行代码运行...但是在这个 wa 中,我应该为每个新的 css 类重复参数值">hot"。
我想要类似的东西
when (@color-type='hot')
{
body { ... }
.myclass { ... }
...
}
我怎样才能获得这个?
这实际上不可能完全像那样(因为您无法将块传递到您正在调用的混合中......您正在尝试做的事情可以在 Sass 中使用 @content 指令)。相反,您可以在 Less 中定义一个 mixin,该 mixin 根据传递的@color-type
变量输出特定块(冷或热)。
a) 具有特定参数的混合:
-
首先,您可以制作一个一般的输出mixin,它不显示任何内容,没有 不管
@color-type
是什么(所以如果调用一个未定义的块,你不会得到错误):.show(@color-type) { }
-
然后定义块(类似于处理媒体的方式 查询,除了这里,您将需要一个额外的 mixin 调用):
.show('cold') { body { color: blu; } .myclass { background: url(cold.png); } } .show('hot') { body { color: red; } .myclass { background: url(hot.png); } }
-
现在你只需要调用mixin。根据您传递的变量,正确的块将是 显示(或者如果没有定义具有该变量的块,则 将没有输出)。 例如,现在你可以调用 show(),传递一个 您之前在某处定义的变量:
@color-type: 'hot'; .show(@color-type);
或直接
.show('hot');
CSS输出将是:
body { color: red; } .myclass { background: url(hot.png); }
b) 警卫:
而不是用分词参数定义混合(例如.show('hot'){ ... }
),您可以使用守卫,如下所示:.show(@color-type) when (@color-type = 'hot') { ... }
),或者像这样:.show() when (@color-type = 'hot') { ... }
如果您之前在某处定义了变量并且只需要调用 mixin.show()
即可返回相应的块:
.show() when (@color-type = 'cold') {
body {
color: blue;
}
.myclass {
background: url(cold.png);
}
}
.show() when (@color-type = 'hot') {
body {
color: red;
}
.myclass {
background: url(hot.png);
}
}
// setting the variable
@color-type: 'hot';
// calling the mixin
.show();
也许也很有趣- 与此主题相关的一些讨论:
问题 #965:Mixins 应该接受 LESS 块