好的,我们说我有一个像这样的Less文件:
// Turquoise
@turquoise: #1ABC9C;
@turquoise-2: #16A085;
// Greens
@green: #2ECC71;
@green-2: #27AE60;
// Blues
@blue: #3498DB;
@blue-2: #2980B9;
// Navy Blues
@navy: #34495E;
@navy-2: #2C3E50;
// Purples
@purple: #9B59B6;
@purple-2: #8E44AD;
// Yellows
@yellow: #F1C40F;
// Oranges
@orange: #F39C12;
@orange-2: #E67E22;
@orange-3: #D35400;
// Reds
@red: #E74C3C;
@red-2: #C0392B;
// Greys
@grey: #ECF0F1;
@grey-2: #BDC3C7;
@grey-3: #95A5A6;
@grey-4: #7F8C8D;
@colour-scheme:
@red, @red-2,
@orange, @orange-2, @orange-3,
@yellow,
@green, @green-2,
@turquoise, @turquoise-2,
@blue, @blue-2,
@purple, @purple-2,
@navy, @navy-2,
@grey, @grey-2, @grey-3, @grey-4
;
我想制作一个类似的mixin
:
.createBG( @colour-array: @colour-scheme, @n: length( @colour-scheme ), @i: 0 ){
&.<[COLOUR-ARRAY[@i] VARIABLE NAME]>{
background-color: extract( @colour-array, @i );
}
.createBG( @colour-array, ( @i + 1 ) )
}
如何使用有效的Less代码替换<[COLOUR-ARRAY[@i] VARIABLE NAME]>
,以便为我提供列表/数组当前索引的变量名。
实施此措施的可靠性和最佳实践方法是什么?
答案 0 :(得分:2)
您可以使用extract
函数本身,只需将颜色变量名称设置为@color-scheme
变量的值,而不是自己赋予变量。在mixin中,@@
可用于将变量的名称解析为其实际颜色值。
@colour-scheme:
red, red-2, orange, orange-2, orange-3, yellow, green, green-2, turquoise, turquoise-2,
blue, blue-2, purple, purple-2, navy, navy-2, grey, grey-2, grey-3, grey-4;
.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
@color: extract(@colour-array, @i);
&.@{color}{
background-color: @@color;
}
.createBG( @colour-array, @n, @i + 1 )
}
.createBG();
由于您还需要颜色名称(作为类名),您必须将名称存储在某个变量中,因此不会有太多减少。但我们仍然可以使用关联数组。下面提供了关联数组的示例。
@colour-scheme:
red #E74C3C, red-2 #C0392B,
orange #F39C12, orange-2 #E67E22, orange-3 #D35400,
yellow #F1C40F,
green #2ECC71, green-2 #27AE60,
turquoise #1ABC9C, turquoise-2 #16A085,
blue #3498DB, blue-2 #2980B9,
purple #9B59B6, purple-2 #8E44AD,
navy #34495E, navy-2 #2C3E50,
grey #ECF0F1, grey-2 #BDC3C7, grey-3 #95A5A6, grey-4 #7F8C8D;
.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
@color-name-hex: extract(@colour-array, @i);
@color-name: extract(@color-name-hex, 1);
@color-hex: extract(@color-name-hex, 2);
&.@{color-name}{
background-color: @color-hex;
}
.createBG( @colour-array, @n, @i + 1 )
}
.createBG();
注意:在v2.6.1中查看this bug,最终可能会破坏您的循环。 虽然会修复 。