You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SASS支持变量重新赋值/增减吗?循环内变量递增实现

SASS循环实现动画延迟逐次递增的正确写法

问题场景

原本为多个子元素设置递增的动画延迟,写法重复冗余:

$dropdown-length: 1.5s;

&:nth-child(2) {
  animation-delay: ($dropdown-length + 0.2s);
}

&:nth-child(3) {
  animation-delay: ($dropdown-length + 0.4s);
}

&:nth-child(4) {
  animation-delay: ($dropdown-length + 0.6s);
}

// ... 重复至nth-child(9)

尝试用@for循环优化时,因变量作用域问题导致失败:

@for $num from 2 through 10 {
  $i: 0;
  &:nth-child(#{$num}) {
    $i: $i + 0.2s;
    animation-delay: ($dropdown-length + $i);
  }
}

错误原因:每次循环都会将$i重置为0,且选择器内部的$i仅在当前选择器作用域内有效,最终所有子元素的动画延迟增量均为0.2s,无法实现逐次递增。

正确实现方式

方法一:通过循环变量直接计算增量

无需额外维护递增变量,利用循环变量$num与起始值的差值计算增量,写法更简洁:

$dropdown-length: 1.5s;

@for $num from 2 through 9 {
  &:nth-child(#{$num}) {
    // 第2个元素增量为0,第3个为0.2s,以此类推
    animation-delay: $dropdown-length + ($num - 2) * 0.2s;
  }
}

方法二:外部变量维护递增值

将递增变量$i声明在循环外部,每次循环后更新变量值,避免作用域内重置:

$dropdown-length: 1.5s;
$i: 0s; // 初始化增量为0

@for $num from 2 through 9 {
  &:nth-child(#{$num}) {
    animation-delay: $dropdown-length + $i;
  }
  $i: $i + 0.2s; // 每次循环后增量增加0.2s
}

关键说明

SASS允许变量重新赋值,但需注意作用域:循环内部声明的变量属于当前迭代的局部作用域,每次迭代都会重新初始化;将变量放在循环外部,就能在迭代中持续更新其值。

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:26:00