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

CSS重复代码优化:animation-delay递增0.1s的批量实现方法

嘿,完全不用手动重复写50遍代码!作为CSS新手碰到这种重复的动画延迟需求太正常了,我给你几个从易到难的实用方案,按需选择就行:

方案1:纯CSS变量 + calc()(最易上手)

这个方法不用额外工具,纯原生CSS就能搞定。你只需要给所有方块写一套通用的动画样式,然后用自定义属性(CSS变量)来控制延迟时间:

/* 所有方块的通用样式 */
.square {
  width: 50px;
  height: 50px;
  background: #3498db;
  margin: 5px;
  animation: bounce 1.5s ease-in-out infinite;
  /* 用变量计算延迟:索引值 × 0.1s */
  animation-delay: calc(var(--delay-index) * 0.1s);
}

/* 动画关键帧示例 */
@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}

然后在HTML里给每个方块设置对应的--delay-index变量(从0开始递增):

<div class="square" style="--delay-index: 0"></div>
<div class="square" style="--delay-index: 1"></div>
<div class="square" style="--delay-index: 2"></div>
<!-- ... 直到第50个设置 --delay-index: 49 -->

这样你只需要复制粘贴div标签,修改后面的数字就行,CSS只写一次,比重复整个动画规则高效太多。

方案2:CSS预处理器循环(适合用Sass/LESS的场景)

如果你平时用Sass、LESS这类预处理器,那循环可以帮你自动生成所有延迟规则,连HTML里的变量都不用手动加:

比如用Sass的@for循环:

.square {
  width: 50px;
  height: 50px;
  background: #3498db;
  margin: 5px;
  animation: bounce 1.5s ease-in-out infinite;
}

/* 自动生成第1到第50个方块的延迟规则 */
@for $i from 0 through 49 {
  .square:nth-child(#{$i + 1}) {
    animation-delay: $i * 0.1s;
  }
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}

编译后会自动生成50条.square:nth-child(n)的规则,你只需要在HTML里放50个<div class="square"></div>就行,完全不用手动设置每个延迟。

方案3:JavaScript动态生成(最省心,适合大量元素)

如果要做50个元素,手动写HTML标签也挺麻烦,用JS动态生成是最省事的,还能灵活调整数量:

<!-- 只需要一个容器 -->
<div class="square-container"></div>
.square-container {
  display: flex;
  flex-wrap: wrap;
}

.square {
  width: 50px;
  height: 50px;
  background: #3498db;
  margin: 5px;
  animation: bounce 1.5s ease-in-out infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}
const container = document.querySelector('.square-container');
// 生成50个方块
for (let i = 0; i < 50; i++) {
  const square = document.createElement('div');
  square.classList.add('square');
  // 直接计算并设置延迟
  square.style.animationDelay = `${i * 0.1}s`;
  container.appendChild(square);
}

这样你连HTML标签都不用手动复制,改个循环数字就能调整方块数量,非常灵活。

总结
  • 纯HTML/CSS开发:优先选方案1,简单易理解;
  • 用预处理器:选方案2,自动生成规则;
  • 允许用JS:选方案3,最省心高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:00:18