注意:添加此答案并不是为了说明现有答案不正确或已过时。所有答案都是有效的,并且仍然有效。这只是提供了一种不同的方法,在我看来,它更复杂一些,但在如何将每个参数称为键值对方面也更灵活。
使用此方法的优点:当需要对值执行任何额外操作时(例如将unit 添加为deg、px或执行任何额外的数学运算等)或动态添加 @property 的供应商前缀。例如,有时您可能只想将transform 作为输入属性传递给mixin,但想为-webkit-transition 添加-webkit-transform,为-moz-transform 添加-moz-transform 等。
在这个方法中,我们利用了... 特性,它允许我们将可变数量的参数传递给mixin,循环遍历传递的每个参数,extract 属性的名称以及附加参数(如持续时间、旋转度数等),然后使用 Less 提供的 merge feature 连接为属性指定的值。
-
+: 用逗号连接属性值,并在 Less v1.5.0 中引入
-
+_: 将属性值与空格连接起来,并在 Less v1.7.0 中引入。
.transition(@args...){
.loop-args(@argCount) when (@argCount > 0) {
.loop-args(@argCount - 1);
@arg: extract(@args, @argCount);
@property: extract(@arg,1);
@duration: extract(@arg,2);
-webkit-transition+: @property @duration;
-moz-transition+: @property @duration;
-o-transition+: @property @duration;
transition+: @property @duration;
}
.loop-args(length(@args));
}
div{
.transition(background, 1s; border-color, 2s; color, 2s);
}
.transform(@args...){
.loop-args(@argCount) when (@argCount > 0) {
.loop-args(@argCount - 1);
@arg: extract(@args, @argCount);
@property: extract(@arg,1);
@param: extract(@arg,2);
-webkit-transform+_: ~"@{property}(@{param})";
-moz-transform+_: ~"@{property}(@{param})";
-o-transform+_: ~"@{property}(@{param})";
transform+_: ~"@{property}(@{param})";
}
.loop-args(length(@args));
}
div#div2{
.transform(rotate, 20deg; scale, 1.5; translateX, 10px);
}
上面的代码编译后会产生以下输出:
div {
-webkit-transition: background 1s, border-color 2s, color 2s;
-moz-transition: background 1s, border-color 2s, color 2s;
-o-transition: background 1s, border-color 2s, color 2s;
transition: background 1s, border-color 2s, color 2s;
}
div#div2 {
-webkit-transform: rotate(20deg) scale(1.5) translateX(10px);
-moz-transform: rotate(20deg) scale(1.5) translateX(10px);
-o-transform: rotate(20deg) scale(1.5) translateX(10px);
transform: rotate(20deg) scale(1.5) translateX(10px);
}
相关答案: