LESS循环混合(Mixin)

5
我在想,编写以下代码的最有效方式是什么:

&:nth-child(1){   .animation-delay(100ms); }
&:nth-child(2){   .animation-delay(120ms);  }
&:nth-child(3){   .animation-delay(140ms);  }

我将把它转化为一个LESS mixin,使动画延迟函数的值在每次迭代中增加20,并且目标是下一个nth-child(+1),最大迭代次数。

非常感谢!

2个回答

7

看文档,我觉得它应该是这样的:

.foo(4);

.foo(@n, @i: 1) when (@i =< @n) {
  &:nth-child(@{i}) {
    .animation-delay(100ms + (@i * 20));
  }
  .foo(@n, (@i + 1));
}

使用LESS2CSS测试,使用animation-delay属性代替您的函数:

.foo(4);

.foo(@n, @i: 1) when (@i =< @n) {
  &:nth-child(@{i}) {
    animation-delay: (100ms + (@i * 20));
  }
  .foo(@n, (@i + 1));
}

生成:

:nth-child(1) {
  animation-delay: 120ms;
}
:nth-child(2) {
  animation-delay: 140ms;
}
:nth-child(3) {
  animation-delay: 160ms;
}
:nth-child(4) {
  animation-delay: 180ms;
}

5

如果我们将迭代的每个实例乘以20,就可以得到我们需要的20个步长增量。由于我们需要从100毫秒开始,所以起点需要是80毫秒(80 + 1 * 20)。

@iterations: 5;

.mixin-loop (@i) when (@i > 0) {
  &:nth-child(@{i}) {
    animation-delay: 80 + @i * 20ms;
  }
  .mixin-loop(@i - 1);
}

.test { 
  .mixin-loop(@iterations);
}

CodePen 上的示例。

1
谢谢!那是一个不错的解决方案。 - Ewinnn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接