打字机效果问题:光标位置远超文本末端
解决打字机光标超出文本末端的问题
问题根源有两个:
h1是块级元素,默认占满父容器宽度,动画里width:100%会让光标跑到容器最右侧,而非文本末尾。- 块级元素的宽度特性导致动画结束后,光标无法精准对齐文本末端。
修改后的代码如下:
HTML(无需改动)
<div class="title"> <h1>Hi, I'm ConnerDE</h1> </div>
CSS 修改方案
.title h1 { color: #fff; font-family: monospace; overflow: hidden; border-right: .15em solid orange; white-space: nowrap; margin: 0 auto; letter-spacing: .15em; /* 让元素宽度收缩到文本实际宽度 */ display: inline-block; /* 步数对应文本字符总数(含空格、标点),这里"Hi, I'm ConnerDE"共16个字符 */ animation: typing 3.5s steps(16, end), blink-caret .5s step-end infinite; } @keyframes typing { from { width: 0 } /* 动画结束时宽度适配文本内容 */ to { width: fit-content; } } @keyframes blink-caret { from, to { border-color: transparent } 50% { border-color: orange } }
核心调整说明
display: inline-block:取消h1的块级特性,让它的宽度仅包裹文本内容。width: fit-content:确保动画结束后,元素宽度刚好匹配文本,光标自然停在文本末端。- 确认
steps()的步数和文本字符数一致:数清文本里的每个字符(包括空格、逗号、单引号),能让打字动画的节奏更贴合字符输出。
内容的提问来源于stack exchange,提问作者ConnerDE
相关产品推荐
相关产品推荐

