如何让打字机动画中逐个出现的新字母均为大写?
实现打字机动画时逐个显示大写字母
方法一:纯CSS实现(最简单)
直接利用CSS的text-transform属性将文本实时转换为大写,配合原有的宽度动画,就能让每个新出现的字母都是大写状态,无需修改核心动画逻辑:
<div class="typewriter"> <h5 data-end="g">Example text to test</h5> </div> <style> .typewriter h5 { overflow: hidden; white-space: nowrap; margin: 0 auto; text-transform: uppercase; /* 新增:强制文本大写 */ border-right: .15em solid orange; /* 补充光标样式,原动画依赖此属性 */ animation: typing 3.5s steps(40, end), blink-caret .75s step-end infinite; } @keyframes typing { from { width: 0 } to { width: 100% } } @keyframes blink-caret { from, to { border-color: transparent } 50% { border-color: orange; } } </style>
说明
text-transform: uppercase会实时将元素内的文本转换为大写,当宽度动画逐步展开时,显示的每一段文本自然都是大写格式,适合不需要保留原文本小写的场景。
方法二:JavaScript控制(更灵活)
如果需要原文本保持小写,仅在打字动画过程中显示大写字母,可以用JS逐个读取原文本字符,转换为大写后插入元素,同时保留光标动画:
<div class="typewriter"> <h5 id="typewriter-text" data-text="Example text to test"></h5> </div> <style> .typewriter h5 { overflow: hidden; white-space: nowrap; margin: 0 auto; border-right: .15em solid orange; animation: blink-caret .75s step-end infinite; } @keyframes blink-caret { from, to { border-color: transparent } 50% { border-color: orange; } } </style> <script> const textEl = document.getElementById('typewriter-text'); const sourceText = textEl.dataset.text; let charIndex = 0; const typeSpeed = 100; // 每个字母的显示间隔(毫秒) function typeCharacter() { if (charIndex < sourceText.length) { textEl.textContent += sourceText.charAt(charIndex).toUpperCase(); charIndex++; setTimeout(typeCharacter, typeSpeed); } } // 启动动画 typeCharacter(); </script>
说明
这种方法完全控制每个字母的显示时机和大小写转换,还可以通过调整typeSpeed参数改变打字速度,适合需要自定义动画节奏或保留原文本的场景。
内容的提问来源于stack exchange,提问作者SEO fKings
相关产品推荐
相关产品推荐

