SASS或LESS关键帧百分比循环

13

我正在测试一些特别的东西,尝试在关键帧内循环以动态地将百分比写入其中。

我已经尝试过类似SASS的东西,但是不起作用。

@keyframes test{

    @for $i from 0 through 100 {
        #{$i}% {
            //do special stuff
        } 
        $i: $i + 1;
    }
我希望它输出:

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

但是我得到了

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

我已经在LESS中测试过了,它也不起作用。

    @a: 0%;

    @keyframes test{

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

    }

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

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

有人可以帮助我吗?


在Sass中的@for循环中,您不需要手动添加到循环中的$i。删除$i: $i + 1;也可以正常工作。 - bookcasey
3个回答

23

如果你这样耍小聪明,它就能够正常工作:

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

1

LESS版本

需要.for mixin。

注意

这是一个非内联js版本,以获得最大兼容性。

输入

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

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

输出

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

LESS 2.7.1版本中是否仍需要使用*.for*混合? - another
不确定您的意思?Less 不支持循环:http://lesscss.org/functions/#functions-overview :如果您感兴趣,请查看此链接 https://github.com/pixelass/homeless,它比 "more-or-less" 更好、更快。 - user950658
我很快就会关闭我的问题。但是我看到有人使用原生LESS进行循环 - another
最终我得到了一个可行的答案(由@Harry提供),而不需要安装外部Less库。[链接](https://dev59.com/iJjga4cB1Zd3GeqPR_pB) - another

1

显然,Sass需要以百分比的形式定义值才能正确渲染。

此示例生成关键帧以动画背景,但您可以更改值列表和要动画的属性。

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 输出

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

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