CSS打字动画未按设定字符数停止问题求助
解决CSS打字动画固定停止位置的问题
你的问题核心在于动画目标宽度固定为16em,而非根据文本长度自适应,同时steps()的数值与实际文本字符数不匹配,导致动画表现和预期不符。以下是具体修复方案:
问题根源拆解
- 当前
@keyframes typewriter的to值是固定的16em,无论文本内容长短,动画都会拉到这个宽度:长文本会被截断,短文本动画结束后会残留空白区域。 steps(50)的步数设置和实际文本字符数不匹配,动画进度是按宽度变化推进的,而非字符数量,所以步数设置无效。
纯CSS修复方案(适配固定文本)
因为使用的是等宽字体Courier Prime,可以用ch单位(1ch等于等宽字体中一个字符的宽度)来精准匹配文本长度:
- 先数出目标文本的实际字符数(包含空格、标点),比如示例中的"Under construction..."共20个字符;
- 将
steps()的数值设为对应字符数,动画目标宽度设为「字符数+1」ch(预留光标宽度,避免文本被截断); - 把
.line的默认宽度改为fit-content,让容器自适应文本。
修改后的完整代码:
@import url('https://fonts.googleapis.com/css2?family=Courier+Prime&family=Source+Code+Pro:wght@200&display=swap'); html { min-height: 100%; overflow: hidden; } body { height: calc(100vh - 8em); padding: 0; margin: 0; color: #FFF; font-family: 'Courier Prime', monospace; background-color: rgb(0, 0, 0); } .video-bg { position: absolute; top: 0; left: 0; min-width: 100%; min-height: 100%; opacity: .5; } .line { position: relative; top: 75%; width: fit-content; /* 改为自适应宽度 */ margin: auto; border-right: 2px solid #FFF; font-size: 18px; text-align: center; white-space: nowrap; overflow: hidden; transform: translateY(-50%); /* 补全原有代码的语法错误 */ } .anim-typewriter { /* 匹配文本字符数设置steps,时长按需调整 */ animation: typewriter 3s steps(20) 1s 1 normal both, blinkTextCursor 750ms infinite normal; } @keyframes typewriter { from { width: 0; } to { width: 21ch; /* 字符数+1ch,预留光标空间 */ } } @keyframes blinkTextCursor { from { border-right-color: transparent; } to { border-right-color: rgb(155, 211, 71); } }
<p class="line anim-typewriter">Under construction...</p>
动态文本适配方案(结合JS)
如果文本内容会动态变化,用JS自动获取字符数并设置动画参数更灵活:
<p class="line anim-typewriter">Under construction...</p> <script> const typeElement = document.querySelector('.anim-typewriter'); const charCount = typeElement.textContent.length; // 自动设置动画参数:时长按字符数比例分配,steps匹配字符数 typeElement.style.animation = `typewriter ${charCount * 0.15}s steps(${charCount}) 1s 1 normal both, blinkTextCursor 750ms infinite normal`; // 动态生成对应字符数的宽度关键帧 const styleSheet = document.createElement('style'); styleSheet.textContent = `@keyframes typewriter { from { width: 0; } to { width: ${charCount + 1}ch; } }`; document.head.appendChild(styleSheet); </script>
这个方案会自动根据文本长度调整动画步数、时长和目标宽度,无需手动计算字符数。
内容的提问来源于stack exchange,提问作者Mason
相关产品推荐
相关产品推荐

