如何用CSS实现逐行依次触发的打字动画效果?
逐行顺序打字动画的优化方案
需求
实现从上到下逐行依次的打字动画,每一行文本按顺序逐个显示,避免为每个元素单独定义关键帧导致代码冗余。
原HTML结构(无需修改)
<div class='screen'> <div class='text-container'> <p class='text'>A problem has been detected and system has been shut down to prevent damage to your computer. </p> <br /> <p class='text'>IRQL_NOT_LESS_OR_EQUAL</p> <br /> <p class='text'>If this is the first time you've seen this Stop error screen, restart your computer.</p> <p class='text'>If this screen appears again, follow these steps:</p> <br /> <p class='text'>Check to make sure any new hardware or soFtware is properly installed.</p> <p class='text'>If this is a new installation,</p> <p class='text'>ask your hardware or soFtware manufacturer for any system updates you might need.</p> <br /> <p class='text'>If problems continue, disable or remove any newly installed hardware or soFtware.</p> <p class='text'>Disable BIOS memory options such as caching or shadowing.</p> <p class='text'>If you need to use Safe Mode to remove or disable components, restart your computer.</p> <p class='text'>press F8 to select Advanced Startup options, and then select Safe Mode.</p> <br /> <p class='text'>Technical information:</p> <br /> <p class='text'>*** STOP: 0x0000000A /0x0000000000004A,</p> <p class='text'>0x0000000000000002, 0x0000000000000001, 0xFFFFF80002B37ABF</p> <br /> <p class='text'>Collecting data for crash dump ...</p> <p class='text'>Initializing disk for crash dump ...</p> <p class='text'>Beginning dump of physical memory.</p> </div> </div>
优化后的SCSS代码
* { padding: 0; margin: 0; box-sizing: border-box; } // 定义全局动画参数 $total-lines: 17; // 统计所有p.text的数量 $typing-duration: 5s; // 单行文本文字逐个显示的时长 $delay-per-line: $typing-duration; // 每行之间的延迟时间(等于单行时长,上一行打完再打下一行) @keyframes typing { from { width: 0; } to { width: 100%; } } div.screen { background-color: #032f7c; div.text-container { padding: 20px; p.text { font-family: monospace; color: #ebf6ff; overflow: hidden; white-space: nowrap; letter-spacing: 1.5px; animation: typing $typing-duration steps(90, end) forwards; width: 0; // 初始宽度设为0,配合动画显示 } // 利用SCSS循环自动为每行设置延迟 @for $i from 1 through $total-lines { p.text:nth-of-type(#{$i}) { animation-delay: ($i - 1) * $delay-per-line; } } } }
方案说明
- 统一关键帧:只保留一套
typing关键帧,所有行共用,避免重复定义。 - SCSS循环批量设置延迟:通过
@for循环计算每行的animation-delay,第一行延迟0s,第二行延迟等于单行打字时长,以此类推,实现上一行打完后下一行才开始打字的顺序效果。 - 动画状态保持:添加
forwards值到animation属性,确保每行文字打完后保持完整显示状态,不会重置回宽度0。 - 参数化管理:把总行数、单行时长、行间隔延迟定义为变量,后续修改只需调整变量值,维护更方便。
如果需要更精准的打字步长,可以给每个p.text添加CSS变量--char-count,然后把steps(90, end)改为steps(var(--char-count), end),比如:
<p class='text' style="--char-count: 85">A problem has been detected...</p>
这样能让每个文本的打字步长完全匹配自身字符数量,动画更精准。
内容的提问来源于stack exchange,提问作者Mehmet Güdük
相关产品推荐
相关产品推荐

