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

求助:纯HTML/CSS实现轮播式CSS动画文本切换效果

解决方案:实现文本依次切换的CSS循环动画

问题分析

当前代码的核心问题:

  • 文本使用相对定位,会占据垂直空间导致堆叠,无法在同一位置显示
  • 动画时长与延迟的配合逻辑错误,导致文本切换衔接不上
  • 缺少容器高度限制,绝对定位文本无法正常显示

修改方案

  1. 统一文本位置:将所有文本设置为绝对定位,让它们重叠在容器的同一位置
  2. 调整动画时间线:设置总动画时长为12秒(4个文本各占3秒周期),通过关键帧控制每个文本的「进入-停留-退出」阶段
  3. 修正容器样式:添加固定高度,确保文本能正常显示
  4. 修正拼写错误:修正文本中的拼写问题

修改后的完整代码

CSS

@keyframes coolAnimation {
    /* 初始/退出后保持隐藏状态 */
    0%, 33.33%, 100% {
        opacity: 0;
        transform: translateY(100%);
    }
    /* 完成进入动画后保持显示 */
    8.33%, 25% {
        opacity: 1;
        transform: translateY(0);
    }
}

#textContainer {
    position: relative;
    overflow: hidden;
    height: 100px; /* 根据字体大小调整,确保文本完整显示 */
}

.coolText {
    color: #000000;
    font-family: 'Myriad Pro', Arial, sans-serif;
    margin: 0;
    font-size: 40px;
    animation: coolAnimation 12s ease-in-out infinite;
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    transform: translateY(100%);
    width: 100%;
    text-align: center; /* 可选:让文本居中对齐 */
}

/* 每个文本延迟递增3秒,实现无缝衔接 */
.coolText:nth-child(1) { animation-delay: 0s; }
.coolText:nth-child(2) { animation-delay: 3s; }
.coolText:nth-child(3) { animation-delay: 6s; }
.coolText:nth-child(4) { animation-delay: 9s; }

HTML

<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Cool Text Animation</title>
    </head>
    <body>
        <div id="textContainer">
            <h3 class="coolText">UTILISATION <br>ILLIMITÉE</h3>
            <h3 class="coolText">SANS <br>CONTACT</h3>
            <h3 class="coolText">SANS <br>ABONNEMENT</h3>
            <h3 class="coolText">ECO-<br>RESPONSABLE</h3>
        </div>
    </body>
</html>

逻辑说明

  • 总动画时长12秒,每个文本的显示周期占3秒(12秒/4个文本)
  • 关键帧百分比对应时间节点:
    • 8.33%:1秒后完成进入动画,开始显示
    • 25%:3秒时开始退出动画
    • 33.33%:4秒时完全隐藏,等待下一轮循环
  • 每个文本的延迟依次递增3秒,刚好在前一个文本退出后立即进入,实现无缝循环切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:52:39