LESS动态调用mixin [英] LESS call a mixin dynamically
问题描述
如何动态调用mixin?
How do you call a mixin dynamically?
一个用例可能是生成一个样式指南:
A use case might be to generate a style guide:
// 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);
$ b
Is such a dynamic call possible at all with less css?
推荐答案
你不能根据需要动态调用。不过,您可以使用模式匹配将其设置略有不同,如下所示:
You cannot at present dynamically call as you desire. You can, however, set it up slightly differently using pattern matching, like so:
// 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);
使用模式匹配,可以创建其他模式,例如:
Using pattern matching, you can then create other patterns, such as:
.typography(xl){
font-family: Arial;
font-size: 32px;
line-height: 44px;
}
.typography(times){
font-family: 'Times New Roman';
font-size: 16px;
line-height: 22px;
}
现在可以调用pattern xl
或 times
并让它生成代码。基本上,取连字符后面要使用的任何内容(如 -xs
)以区分各种排版组,并删除连字符,并使用该名称作为您的模式匹配mixins。
Now you can call pattern xl
or times
and have it generate the code. Essentially, take whatever you were going to use after the hyphen (like your -xs
) to distinguish your various typography groups, and remove the hyphen and use that name as your pattern to match the mixins to.
此外,我将添加一个方法在 @ {typographyName}
像这样:
Additionally, I would add a means of putting a selector before the @{typographyName}
like so:
.typography-demo(@typographyName, @selector: ~".") {
@{selector}@{typographyName} {
&:before{content: '@{typographyName}';}
// Calling the mixin dynamically
.typography(@typographyName);
}
}
这种方式默认生成一个类,可以创建为直到 @ {typographyName}
的id或任何选择器字符串。
This way it generates a class by default, but could be made into an id or any selector string up to the @{typographyName}
.
这篇关于LESS动态调用mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!