SASS中如何通过循环动态命名@keyframes?
Sass循环动态生成命名@keyframes的解决方案
问题背景
需要生成一组命名为loading-1至loading-7的CSS动画,每个动画在对应百分比位置设置元素透明度为0.3,示例目标CSS如下:
@keyframes loading-1 { 14.28% { opacity: 0.3; } } @keyframes loading-2 { 28.57% { opacity: 0.3; } } /* loading-3至loading-7 以此类推 */
尝试编写的Sass代码编译时出现Error: expected "}"错误,报错指向@keyframes loading-#{$l} {行。
问题分析与修复
你的代码存在两处核心问题:
- 关键帧百分比语法错误:不能用大括号包裹函数调用,必须使用Sass的插值语法
#{}直接嵌入计算结果 - 百分比计算逻辑错误:原代码
100/$l的计算结果不符合需求,正确逻辑应为$l * (100 / $number-of-steps)(即序号乘以单步百分比)
修正后的完整代码
$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}`."; } $pow: pow(10, $digits); @return round($float * $pow) / $pow; } @for $l from 1 through $number-of-steps { @keyframes loading-#{$l} { #{to-fixed($l * (100 / $number-of-steps), 2)}% { opacity: 0.3; } } }
验证结果
上述代码可通过最新版VSCode Live SASS Compiler正常编译,生成的CSS完全符合需求:每个loading-N动画的关键帧百分比为N * (100/7)的两位小数近似值,对应14.28%、28.57%直至100%。
关键说明
Sass完全支持通过#{$变量名}的插值语法动态生成@keyframes的名称,你遇到的报错并非动态命名本身的问题,而是关键帧内部的语法错误导致的编译失败。
内容的提问来源于stack exchange,提问作者Carl S
相关产品推荐
相关产品推荐

