本文详解如何通过 CSS 实现无限循环的打字效果,并解决动画末尾卡顿问题,重点修正 animation 属性覆盖 animation-iteration-count 的常见错误,同时优化关键帧时序以确保节奏均匀。
本文详解如何通过 css 实现无限循环的打字效果,并解决动画末尾卡顿问题,重点修正 `animation` 属性覆盖 `animation-iteration-count` 的常见错误,同时优化关键帧时序以确保节奏均匀。
要实现真正平滑、无限循环的 CSS 打字动画,需同时解决两个核心问题:动画无法循环和结尾明显减速/停顿。根本原因在于 CSS 动画声明的优先级与关键帧设计逻辑。
原始代码中单独设置 animation-iteration-count: infinite 是无效的,因为后续的 animation 简写属性(如 animation: typing 5s forwards)会完全重置所有子属性,包括迭代次数,默认为 1。正确做法是将 infinite 直接写入 animation 简写中:
@keyframes typing { from { width: 0; } to { width: 100%; }}.typed-out { overflow: hidden; border-right: 0.15em solid #990000; white-space: nowrap; font-family: 'Dosis', sans-serif; /* ✅ 关键:infinite 必须放在 animation 简写中 */ animation: typing 5s steps(30, end) forwards infinite; width: 0;}
? steps(30, end) 是关键优化:它将动画划分为 30 个等距阶跃(step),模拟逐字输入效果,避免 from→to 线性插值导致的末尾“拖尾”或视觉减速。end 表示在每步结束时跳变,更符合打字节奏。
<!DOCTYPE html><html dir="rtl" lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Typing Animation Infinite</title> <link href="https://fonts.googleapis.com/css?family=Dosis&display=swap" rel="stylesheet"> <style> @keyframes typing { from { width: 0; } to { width: 100%; } } .typed-out { display: inline-block; overflow: hidden; border-right: 0.15em solid #990000; white-space: nowrap; font-family: 'Dosis', sans-serif; font-size: 1.8rem; /* 使用 steps() + infinite 实现流畅循环 */ animation: typing 4s steps(25, end) forwards infinite; width: 0; } </style></head><body> <div class="container d-flex justify-content-center align-items-center vh-100"> <h2 class="typed-out">This is a Typing Text</h2> </div></body></html>
掌握 animation 简写语法优先级与 steps() 函数的精准应用,即可轻松构建专业级、无限循环且节奏稳定的 CSS 打字动画。
立即学习“前端免费学习笔记(深入)”;