我正在为 WordPress 网络创建一个主题系统,该系统支持多种布局主题,可以支持各种大学的配色方案。为此,我定期编译一个带有学校特定变量的 LESS 文件(使用 lessphp),并实质上将其用作主题中的辅助类库。
每所学校都有 3 种颜色,在 LESS 中定义为:@primary
, @secondary
and @tertiary
。该方法简单且实用,但需要大量重复代码。例如:
//Modifier Classes
.primary-lighter-text {
color: lighten(@primary,20);
}
.sec-lighter-text {
color: lighten(@secondary,20);
}
.tert-lighter-text {
color: lighten(@tertiary,20);
}
//Backgrounds
.primary-bg {
background-color: @primary;
}
.sec-bg {
background-color: @secondary;
}
.tert-bg {
background-color: @tertiary;
}
//Borders
.primary-border{
border-color: @primary;
}
.sec-border {
border-color: @secondary;
}
.tert-border {
border-color: @tertiary;
}
从 LESS 的角度来看,没什么复杂的,但如果我想添加一个新的帮助器类,我必须创建 3 个。有没有更简洁的方法来实现这一点?
您可以通过使用数组循环来简化它。如果有新添加,您需要修改的就是修改末尾的数组变量。
.loop-column(@index) when (@index > 0) { /* Recursive Mixin with Guard condition. Mixin is processed only when the condition is satisfied */
.loop-column(@index - 1); /* Call the mixin again with a decremented counter */
@ctype: extract(@type, @index); /* Extract the type value corresponding to the index from the array */
@color: extract(@colors, @index); /* Extract the color value corresponding to the index from the array */
/* Form and Output the necessary classes and properties */
.@{ctype}-lighter-text { /* Selector interpolation to dynamically form the selector */
color: lighten(@color,20);
}
.@{ctype}-bg {
background-color: @color;
}
.@{ctype}-border{
border-color: @color;
}
}
.loop-column(length(@type));
@type: primary, sec, tert; /* The color types array */
@colors:#fff, #777, #000; /* The color value array for each type */
/* If required the colors can be kept as separate variables also. Refer 2nd demo. */
Demo | Demo 2
Update:(根据评论安德鲁·卡弗雷克 and 最多七相)
由于 LessPHP 已过时,因此应添加以下行并length(@type)
应替换为实际计数。
.loop-column(0) {};
.loop-column(4);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)