【发布时间】:2013-08-13 16:58:17
【问题描述】:
我正在尝试在 LESS 中制作可变参数 mixin。为此,我对我的 mixin 使用以下语法:
.mixin (@a; @rest...) {
// @rest is bound to arguments after @a
// @arguments is bound to all arguments
}
但我不知道如何操作@rest 并读取到mixin 的最后一个参数。
这是我的代码:
.color () { }
.color (@shade) {
#id {
background-color : rgb(@shade, @shade, @shade);
}
}
.color (@shade, @rest...) {
#id {
background-color : rgb(@shade, @shade, @shade);
}
.color(@rest);
}
.color(200, 160);
正如你猜想的那样,这个 mixin 应该检查整个参数列表,并使用与 mixin 的最后一个参数对应的灰色阴影(在本例中为 rgb(160, 160, 160))。
但是当我用 less-1.4.1.js 编译这段代码时,我得到以下错误:
SyntaxError: error evaluating function `rgb`:
color functions take numbers as parameters
那么如何获取mixin的第二、第三、第四……参数呢?
非常感谢您的建议,周末愉快!
编辑
This 完美运行,非常感谢!
但是我想问另一个问题。假设我的 mixin 是可变参数的,它需要至少一个与其余参数(例如字符串或其他数字)无关的参数,但必须对其进行处理,以便可能调用以前的 mixin 可能是:
.color("first argument", 200, 160);
.color(-42, 200, 160);
.color(3, 200, 160); // 3 doesn't need to be processed in the loop
换句话说,.loop 应该从第二个参数开始检查 mixin 的所有参数,并对第一个参数应用不同的过程。所以我需要把mixin的骨架改成这样:
.color(...) {
...; // Handling the first parameter
.loop (@arguments); // Handling the rest of the parameters
}
但在您的解决方案中,变量 @arguments 包含整个参数列表,包括第一个。如何在不玩 isnumber() 的情况下将其从列表中排除?
我确切地说,实际上在我的项目中,从第二个开始的每个参数都被处理,所以:
.loop(@list, @index: 1, @shade: NULL) when not (isnumber(@list)) and (isnumber(extract(@list, @index))) {
.loop(@list, (@index + 1), extract(@list, @index));
}
变成
.loop(@list, @index: 1, @shade: NULL) when not (isnumber(@list)) and (isnumber(extract(@list, @index))) {
.loop(@shade);
.loop(@list, (@index + 1), extract(@list, @index));
}
而且这个过程不在于简单地改变固定<div> 的背景颜色;)但我想简化我的问题。
非常感谢您的回答和宝贵的建议!
编辑,再次:马丁,您向我推荐的内容非常有效。再次感谢!
【问题讨论】: