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

如何在CSS中让动画元素保持最终状态直至其余动画完成

实现目标均衡器动画的解决方案

核心思路

要实现依次增高并保持高度的动画效果,需要给每个条形设置带延迟的动画,并在关键帧中加入保持阶段,确保条形到达目标高度后停留,同时按指定顺序启动动画。

修改后的完整代码

CSS 代码

.equilizer {
  height: 100px;
  width: 100px;
  transform: rotate(180deg);
}

.bar {
  width: 18px;
  height: 0; /* 初始高度设为0 */
}

/* 红色条:先上升到50px,保持后重置 */
.bar-4 {
  animation: red-bar 4s infinite;
  fill: #ad1e23;
}

/* 黄色条:延迟1s后上升到100px,保持后重置 */
.bar-3 {
  animation: yellow-bar 4s 1s infinite both;
  fill: #e5a32b;
}

/* 第一个绿色条:延迟2s后上升到75px,保持后重置 */
.bar-2 {
  animation: green-bar 4s 2s infinite both;
  fill: #416031;
}

/* 第二个绿色条:延迟3s后上升到75px,保持后重置 */
.bar-1 {
  animation: green-bar 4s 3s infinite both;
  fill: #416031;
}

@keyframes red-bar {
  0% { height: 0; }
  25% { height: 50%; } /* 0-1s:上升到目标高度 */
  90% { height: 50%; } /* 1-3.6s:保持目标高度 */
  100% { height: 0; } /* 3.6-4s:重置为初始状态 */
}

@keyframes yellow-bar {
  0% { height: 0; }
  25% { height: 100%; } /* 1-2s:上升到目标高度 */
  75% { height: 100%; } /* 2-3.6s:保持目标高度 */
  100% { height: 0; } /* 3.6-4s:重置为初始状态 */
}

@keyframes green-bar {
  0% { height: 0; }
  25% { height: 75%; } /* 延迟后1s内上升到目标高度 */
  50% { height: 75%; } /* 保持目标高度直到循环末期 */
  100% { height: 0; } /* 重置为初始状态 */
}

HTML 代码

<svg xmlns="http://www.w3.org/2000/svg" class="equilizer" viewBox="0 0 128 128">
  <g>
    <title>Audio Equalizer</title>
    <rect class="bar bar-1" transform="translate(0,0)" y="15" rx="10"></rect>
    <rect class="bar bar-2" transform="translate(25,0)" y="15" rx="10"></rect>
    <rect class="bar bar-3" transform="translate(50,0)" y="15" rx="10"></rect>
    <rect class="bar bar-4" transform="translate(75,0)" y="15" rx="10"></rect>
  </g>
</svg>

关键调整说明

  1. 添加动画延迟:通过animation-delay让条形按顺序启动(红色→黄色→绿色→绿色)
  2. 设置保持阶段:在关键帧中用多个百分比节点锁定目标高度,确保条形到达后停留
  3. 统一动画节奏:总时长设为4s,各阶段占比匹配目标动画的时序
  4. 优化初始状态:给所有条形设置初始高度为0,避免默认高度干扰动画

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:30:59