简体   繁体   中英

LESS Mixin for loop

I was wondering what is the most efficient way to write this:

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

.. into some LESS mixin that will set the animation-delay function value to +20 every iteration, while the next nth-child (+1) will be targeted, with a max iteration.

Thanks so much!

Looking at the docs I'd say it would look like:

.foo(4);

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

Tested with LESS2CSS using animation-delay property instead of your function:

.foo(4);

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

Generates:

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

If we take each instance of the iteration and multiply it by 20 we get the 20 step increments we need. Since we need to start at 100ms the starting point needs to be 80ms (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);
}

Example on CodePen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM