使用CSS实现打字机效果
<h2>实现效果</h2><p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202310/20231023140605491.gif" /></p>
<p><a href="https://codepen.io/oxxd/pen/NWoWgZa" target="_blank">在线演示</a></p>
<h2>实现</h2>
<p>HTML 元素:</p>
<div class="jb51code"><pre class="brush:xhtml;"><div class="typewriter">
<h1 class="typing">The cat and the hat.</h1>
</div></pre></div>
<p>实现打字机效果的关键是两个动画效果,文字出现的动画,和光标闪烁出现的动画。</p>
<p>这两个动画的实现方式也很简单,文字出现的打字机动画只通过控制元素长度即可。光标闪烁出现可以通过添加右边框,并且给边框添加颜色动画实现。</p>
<div class="jb51code"><pre class="brush:css;">/* 打字机动画 */
@keyframes typing {
from { width: 0 }
to { width: 100% }
}</pre></div>
<div class="jb51code"><pre class="brush:css;">/* 光标动画 */
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: orange }
}</pre></div>
<p>然后将动画效果添加到指定的元素上即可。</p>
<div class="jb51code"><pre class="brush:css;">.typewriter .typing {
color: #fff;
font-family: monospace;
overflow: hidden; /* 保证文字在动画之前隐藏 */
border-right: .15em solid orange; /* 使用边框实现光标 */
white-space: nowrap;
margin: 0 auto;
letter-spacing: .15em;
animation:/** 动画效果 */
typing 3.5s steps(30, end),
blink-caret .5s step-end infinite;
}</pre></div>
<p>结合 <code>Javascript</code> 来控制样式类显示隐藏时机,可以轻松为不同文本实现打字机效果。</p>
頁:
[1]