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

CSS动画第二次播放时div元素消失的问题求助

解决CSS多动画同步及元素消失问题

问题原因

  • 多个动画周期不匹配:move-away总周期为10s×7 +3s=73s,color-change为5s×6+0s=30s,big-to-small为7s×6+3s=45s。当某一动画先结束后,元素会重置为初始样式,而move-away初始状态是margin-left:100%,直接让元素移出视口,看起来像消失。
  • 未设置animation-fill-mode:默认值none会让动画结束后元素回到初始样式,放大了不同步带来的问题。

修复步骤

  1. 统一动画周期:调整各动画的时长、迭代次数和延迟,让总周期一致,避免部分动画先结束导致样式重置。
  2. 添加animation-fill-mode: forwards:让所有动画结束后保持最后一帧样式,不会回到初始状态。
  3. 修正move-away动画逻辑:确保动画全程元素在视口内,避免初始/结束状态导致元素移出。

修改后的代码

CSS部分

div {
  width: 100px;
  height: 100px;
  padding: 5px;
  /* 统一总周期为30s:时长×迭代次数 = 一致,取消延迟避免错位 */
  animation-duration: 10s, 5s, 10s;
  animation-direction: alternate-reverse, alternate, alternate;
  animation-delay: 0s, 0s, 0s;
  animation-iteration-count: 3, 6, 3;
  animation-name: move-away, color-change, big-to-small;
  /* 动画结束后保持最后一帧样式 */
  animation-fill-mode: forwards;
}

p {
  color: white;
  text-align: center;
  user-select: none;
}

@keyframes move-away {
  from {
    margin-left: 0; /* 初始位置在视口内 */
  }
  to {
    margin-left: calc(100% - 110px); /* 计算后避免元素移出视口(宽度+左右padding) */
  }
}

@keyframes color-change {
  from {
    background-color: #DCAB6B;
  }
  25% {
    background-color: #7d4f50;
  }
  50% {
    background-color: #8f250c;
  }
  75% {
    background-color: #583101;
  }
  to {
    background-color: #000000;
  }
}

@keyframes big-to-small {
  from {
    padding: 5px;
  }
  50% {
    padding: 20px;
  }
  to {
    padding: 5px;
  }
}

HTML部分

<div>
  <p>Animation</p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:01:05