從打字機效果的N種實現看JS定時器機制和前端動畫
阿新 • • 發佈:2021-07-14
打字機效果的 N 種實現
實現一:setTimeout()
setTimeout版本的實現很簡單,只需把要展示的文字進行切割,使用定時器不斷向DOM元素裡追加文字即可,同時,使用::after偽元素在DOM元素後面產生游標閃爍的效果。程式碼和效果圖如下:
<!-- 樣式 -->
<style type="text/css">
/* 設定容器樣式 */
#content {
height: 400px;
padding: 10px;
font-size: 28px;
border-radius: 20px;
background-color: antiquewhite;
}
/* 產生游標閃爍的效果 */
#content::after{
content: '|';
color:darkgray;
animation: blink 1s infinite;
}
@keyframes blink{
from{
opacity: 0;
}
to{
opacity: 1;
}
}
</style>
<body>
<div id='content'></div>
<script>
(function () {
// 獲取容器
const container = document.getElementById('content')
// 把需要展示的全部文字進行切割
const data = '最簡單的打字機效果實現'.split('')
// 需要追加到容器中的文字下標
let index = 0
function writing() {
if (index < data.length) {
// 追加文字
container.innerHTML += data[index ++]
let timer = setTimeout(writing, 200)