如何动态调用 mixin?
用例可能是生成风格指南:
// The mixin which should be called
.typography-xs(){
font-family: Arial;
font-size: 16px;
line-height: 22px;
}
// The mixin which tries to call typography-xs
.typography-demo(@typographyName, @mixinName) {
@{typographyName} {
&:before{content: '@{typographyName}';}
// Calling the mixin dynamically
@mixinName();
}
}
// Example call of .typograhpy-demo
.typography-demo(xs, typography-xs);
是否可以使用更少的 css 进行这样的动态调用?
最佳答案
您目前不能随心所欲地动态调用。但是,您可以使用 pattern matching 进行稍微不同的设置。 ,像这样:
// The mixin which should be called
.typography(xs){
font-family: Arial;
font-size: 16px;
line-height: 22px;
}
// The mixin which tries to call typography-xs
.typography-demo(@typographyName) {
@{typographyName} {
&:before{content: '@{typographyName}';}
// Calling the mixin dynamically
.typography(@typographyName);
}
}
// Example call of .typograhpy-demo
.typography-demo(xs);
使用模式匹配,您可以创建其他模式,例如:
.typography(xl){
font-family: Arial;
font-size: 32px;
line-height: 44px;
}
.typography(times){
font-family: 'Times New Roman';
font-size: 16px;
line-height: 22px;
}
现在您可以调用模式 xl
或 times
并让它生成代码。本质上,在连字符之后使用任何你要使用的东西(比如你的 -xs
)来区分你的各种排版组,然后删除连字符并使用该名称作为你的模式来匹配 mixins。
此外,我会添加一种在 @{typographyName}
之前放置选择器的方法,如下所示:
.typography-demo(@typographyName, @selector: ~".") {
@{selector}@{typographyName} {
&:before{content: '@{typographyName}';}
// Calling the mixin dynamically
.typography(@typographyName);
}
}
默认情况下,它会生成一个类,但可以生成一个 id 或任何选择器字符串,直到 @{typographyName}
。
关于css - LESS 动态调用 mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798871/