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

CSS动画求助:多段fadeout动画结束后首段从头循环实现

实现多行fadeout动画循环播放

核心逻辑

先算出所有行里最长的动画时长(也就是最后一行动画结束的时间点),等这个时间到了,就重置所有行的动画状态,让第一行从头开始播放,以此形成循环。

代码实现示例

HTML结构

<div class="text-container">
  <p class="fade-text" style="animation-duration: 2s;">第一行内容</p>
  <p class="fade-text" style="animation-duration: 3s;">第二行内容</p>
  <p class="fade-text" style="animation-duration: 4s;">第三行内容</p>
</div>

CSS动画定义

.fade-text {
  opacity: 1;
  animation: fadeout linear forwards;
}

@keyframes fadeout {
  to {
    opacity: 0;
  }
}

JavaScript控制循环

const fadeTexts = document.querySelectorAll('.fade-text');
// 提取所有行的动画时长,找出最长的那个(循环周期)
const maxDuration = Math.max(...Array.from(fadeTexts).map(item => parseFloat(item.style.animationDuration)));

function restartCycle() {
  fadeTexts.forEach(item => {
    // 先移除动画
    item.style.animation = 'none';
    // 强制浏览器重绘,确保动画能重新触发
    void item.offsetWidth;
    // 恢复动画,让元素从头执行fadeout
    item.style.animation = null;
  });
}

// 每隔最长时长重启一次动画循环
setInterval(restartCycle, maxDuration * 1000);

注意点

  • 如果后续行的数量或动画时长有变化,记得在每次循环前重新计算最长时长,保证循环周期和最后一行结束时间匹配。
  • void item.offsetWidth这一步很关键,它能强制浏览器重绘元素,否则直接移除再恢复动画可能不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:46:18