SASS or LESS Keyframes percentage loop

亡梦爱人 提交于 2019-12-10 16:26:52

问题


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 ?


回答1:


It will work if you finagle it like this:

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



回答2:


LESS version

requires the .for mixin

  • https://github.com/pixelass/more-or-less/blob/master/less/fn/_for.less

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
}



回答3:


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; } 
}


来源:https://stackoverflow.com/questions/15994136/sass-or-less-keyframes-percentage-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!