从 LESS >= 1.7 开始,您可以将变量用于关键帧关键字(名称)。
LESS 1.7 对指令的工作方式进行了一些更改,允许使用变量作为 @keyframes 的名称/关键字(因此问题中的示例现在应该可以使用)。
很遗憾,LESS 中无法动态生成关键帧名称
因此,处理关键帧的正常方式将使用硬编码名称,并且您只需要调用特定的“for”和“to”mixin,如下所示:
.colors-mixin-frame(@from,@to){
from {color: @from;}
to {color: @to;}
}
.width-mixin-frame(@from,@to){
from {width: @from;}
to {width: @to;}
}
// keyframes with hardcoded names calling for specific mixin frames
@keyframes red-blue { .colors-mixin-frame(red, blue); }
@keyframes change-width { .width-mixin-frame(254px, 512px); }
但您可以使用变通方法来动态生成名称
在将名称注入规则名称的地方,这需要声明下一个规则,该规则在关键帧声明的末尾提供右括号 }。最方便的是,如果您只是构建调用该关键帧的动画
.animation-keyframes(@name, @from, @to, @anim-selector) {
@keyf: ~"@keyframes @{name} { `'\n'`from ";
@anim: ~"} `'\n'`.@{anim-selector}";
@{keyf} {
.from(@name,@from);
}
to {
.to(@name,@to);
}
@{anim} {
animation-name:@name;
}
}
请注意,您还需要定义 .from(){} 和 .to(){} 混合,而不仅仅是像在示例中那样使用 @from 和 @to(因为 LESS 也不允许动态生成的属性).. . 这个 mixins 现在可以构造所需的属性和值 ... 要使用特定属性,您可以使用守卫或特定名称的 mixins,如下所示:
// name-specific from and to mixins that are used if first argument equals "colors"
.from (colors, @color) {
color: @color;
}
.to (colors, @color) {
color: @color;
}
现在我们可以在 LESS 中调用我们的 mixin:
// test
.animation-keyframes (colors, red, blue, my-colanim);
并获得 CSS:
@keyframes colors {
from {
color: #ff0000;
}
to {
color: #0000ff;
}
}
.my-colanim {
animation-name: colors;
}
这也适用于 LESS 1.4,但请注意,我们使用 javascript 插值来换行,这需要 LESS 的 javascript 实现。
编辑:关于前缀的其他问题
与供应商前缀混合
在这里我做了两个 mixin ... 一个没有供应商前缀,一个同时调用通用 .keyframes mixin:
.keyframes (@name, @from, @to, @vendor:"", @bind:"") {
@keyf: ~"@{bind}@@{vendor}keyframes @{name} { `'\n'`from ";
@{keyf} {
.from(@name,@from);
}
to {
.to(@name,@to);
}
}
.animation-keyframes-novendor (@name, @from, @to, @anim-selector) {
.keyframes (@name, @from, @to);
@anim: ~"} `'\n'`.@{anim-selector}";
@{anim} {
animation-name:@name;
}
}
.animation-keyframes (@name, @from, @to, @anim-selector) {
@bind: "} `'\n'`";
.keyframes (@name, @from, @to, "-moz-");
.keyframes (@name, @from, @to, "-webkit-", @bind);
.keyframes (@name, @from, @to, "-o-", @bind);
.keyframes (@name, @from, @to, "-ms-", @bind);
.keyframes (@name, @from, @to, "", @bind);
@anim: ~"} `'\n'`.@{anim-selector}";
@{anim} {
-moz-animation: @name;
-webkit-animation: @name;
-o-animation: @name;
-ms-animation: @name;
animation: @name;
}
}
.from (colors, @color) {
color: @color;
}
.to (colors, @color) {
color: @color;
}
/* keyframes with all vendor prefixes */
.animation-keyframes (colors, red, blue, my-colanim);
/* keyframes with no vendor prefix */
.animation-keyframes-novendor (colors, red, blue, my-colanim);
.animation-keyframes 现在将为所有供应商前缀和带有供应商前缀属性的动画选择器生成关键帧。正如预期的那样,.animation-keyframes-novendor 提供与上述简单解决方案相同的输出(没有供应商前缀)。
一些注意事项:
animation: @name ease-in-out 2s infinite alternate;
#namespace > .keyframes () // see .less source in the demo for details