如何在 SASS 中*命名*@keyframes?

How to *named* @keyframes in SASS?

提问人:Carl S 提问时间:11/8/2023 更新时间:11/9/2023 访问量:23

问:

我正在尝试使用 SASS 中的循环创建以下一组命名@keyframes

@keyframes loading-1 {
    14.28% {
        opacity: 0.3;
    }
}

@keyframes loading-2 {
    28.57% {
        opacity: 0.3;
    }
}

@keyframes loading-3 {
    42.86% {
        opacity: 0.3;
    }
}

@keyframes loading-4 {
    57.14% {
        opacity: 0.3;
    }
}

@keyframes loading-5 {
    71.43% {
        opacity: 0.3;
    }
}

@keyframes loading-6 {
    85.71% {
        opacity: 0.3;
    }
}

@keyframes loading-7 {
    100% {
        opacity: 0.3;
    }
}

我一直在查看包括 StackOverflow 在内的几个参考资料,但没有一个能解决我试图完成的@keyframe命名类型,我真的不认为有任何重复的帖子可以解决这个问题。

我希望能够做这样的事情:

$number-of-steps: 7;

@function to-fixed($float, $digits: 2) {
    $sass-precision: 5;
    
    @if $digits > $sass-precision {
      @warn "Sass sets default precision to #{$sass-precision} digits, and there is no way to change that for now."
      + "The returned number will have #{$sass-precision} digits, even if you asked for `#{$digits}`."
      + "See https://github.com/sass/sass/issues/1122 for further informations.";
    }
    
    $pow: pow(10, $digits);
    @return round($float * $pow) / $pow;
}

   :


@for $l from 1 through $number-of-steps {

    @keyframes loading_#{$l} {
        {to-fixed((100/$l), 2)}% {
            opacity: 0.3;
        }
    }

}

但 SASS 抱怨

Compilation Error
Error: expected "}".
   ╷
18 │     @keyframes loading-#{$l} {
                                   ^

有没有办法动态创建这些关键帧的名称?

我在 Visual Code Studio 中使用“Live SASS 编译器”,它似乎是最新的。

TIA!

css css-animations live-sass-编译器

评论

0赞 Gabriele Petrioli 11/9/2023
您缺少 .此外,逻辑是颠倒的,因此您可以获得 100% 的不透明度和 14.29% 的不透明度。查看(更新)工作演示#to-fixedloading-1loading-7

答:

0赞 Arkellys 11/9/2023 #1

你的问题不是动态名称,你有两个语法错误。首先是你的插值中缺少:#to-fixed

#{to-fixed((100/$l), 2)}% {
  opacity: 0.3;
}

其次是你对 pow() 的使用,这个函数不能按原样使用,你必须从以下位置导入它:sass:math

@use "sass:math";
$pow: math.pow(10, 2);

请注意,自 v1.25.0 起仅与 Dart Dass 兼容。pow()