简体   繁体   中英

SASS or LESS Keyframes percentage loop

I'm testing something special and I'm trying to loop inside keyframes to dynamically write percentages into it.

I've tested something like that with SASS but it doesn't work.

@keyframes test{

    @for $i from 0 through 100 {
        #{$i}% {
            //do special stuff
        } 
        $i: $i + 1;
    }

I want it to output :

@keyframes test{
    0%{
          ...
    }
    1%{
          ...
    }
    2%{
          ...
    }
    3%{
          ...
    }
    ...
}

But I got

Error on line number: 23. Invalid CSS after "    #{$i}%": expected placeholder name, was " {"

I've tested this in LESS and it doesn't work either.

    @a: 0%;

    @keyframes test{

       .func (@a, @b, @c);

    }

    .func (@a, @b, @c) when (@a < 100%){  
        (@a){
            //do special stuff
        }

        .func (@a+1, @b, @c);
    }

Can someone help me ?

It will work if you finagle it like this:

@keyframes test {
  @for $i from 0 through 100 {
    #{$i * 1%} {
      // do special stuff
    } 
  }
}

LESS version

requires the .for mixin

NOTICE

This is a NON inline-js version for maximum compatibility

INPUT

@keyframes crazy {
    .for(0,100);.-each(@i){
        @selector: e('@{i}%');

        @{selector} {
            /* do crazy stuff */
        }
    }
}

OUTPUT

@keyframes crazy {
  0% {
    /* do crazy stuff */
  }
  1% {
    /* do crazy stuff */
  }
  2% {
    /* do crazy stuff */
  }
  3% {
    /* do crazy stuff */
  }
  4% {
    /* do crazy stuff */
  }
    ...etc
}

Sass apparently needs a value defined as percentage for it to render correctly. This example generates keyframes to animate a background, but you can change both the list of values and the property to animate.

SASS


//Given a list of colors
$COLORS: $COLOR-MAIN #f39d75 #c1cecd #f3f57e

// Define a mixin
=animate-color-keyframes($list: $COLORS, $property: background)
    //declare the first keyframe statically
    0%
        #{$property}: nth($list, -1)
    @for $i from 1 through length($list)
        // calculate the keyframe percentage
        $percentage: $i / length($list)
        $keyframe: percentage($percentage)
        // render keyframes
        #{$keyframe}
            #{$property}: nth($list, $i)

// .....
@keyframes change-bg-color
    +animate-color-keyframes

CSS OUTPUT


@keyframes change-bg-color {
  0% {
    background: #f3f57e; }
  25% {
    background: #abf0b3; }
  50% {
    background: #f39d75; }
  75% {
    background: #c1cecd; }
  100% {
    background: #f3f57e; } 
}

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