CSS打字机动画光标遮挡字符问题的纯CSS修复方案咨询
纯CSS修复打字机动画光标遮挡文字问题
嘿,这个问题完全可以用纯CSS搞定,根本不用碰JavaScript!咱们先捋清楚问题根源:你现在用元素的border-right来模拟光标,这个边框属于元素盒模型的一部分,当typewriter动画把元素宽度从0拉到刚好容纳文字的24em时,光标会紧贴最后一个字符的右侧,视觉上就像挡住了部分内容。
修复方案:用伪元素独立实现光标
我们把光标从元素自身的边框改成伪元素,让它脱离文字内容的布局流,这样就能彻底避免重叠问题。修改后的代码如下:
调整核心样式
/* Google Fonts */ @import url(https://fonts.googleapis.com/css?family=Anonymous+Pro); /* Global */ html{ min-height: 100%; overflow: hidden; } body{ height: calc(100vh - 8em); padding: 4em; color: rgba(255,255,255,.75); font-family:'Anonymous Pro' ,monospace ; background-color: black; } .line-1{ position: relative; top: 50%; width: 24em; margin: 0 auto; /* 移除原有的border-right */ font-size: 180%; text-align: center; white-space: nowrap; overflow: hidden; transform: translateY(-50%); } /* 新增伪元素作为独立光标 */ .line-1::after { content: ''; position: absolute; top: 0; right: 0; height: 100%; width: 4px; background-color: green; animation: blinkTextCursor 1000ms steps(1) infinite normal; } /* Animation */ .anim-typewriter{ animation: typewriter 100s steps(44) 1s 1 normal both; /* 移除原绑定的blinkTextCursor动画 */ } @keyframes typewriter{ from{width: 0;} to{width: 24em;} } @keyframes blinkTextCursor{ from{background-color: green;} to{background-color: transparent;} }
HTML部分无需改动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link href='https://fonts.googleapis.com/css?family=Electrolize' rel='stylesheet'> <title> Test </title> </head> <body> <p class="line-1 anim-typewriter">Animation typewriter style using css steps()</p> </body> </html>
为什么这个方案有效?
伪元素是绝对定位在.line-1的右侧,它的宽度不会占用文字内容的布局空间,文字可以完整显示,光标则在文字右侧独立闪烁。你还可以根据喜好调整伪元素的width改变光标粗细,或者加个right: -6px;让光标和文字之间留一点空隙,视觉效果会更自然。
内容的提问来源于stack exchange,提问作者darkchampionz
相关产品推荐
相关产品推荐

