使用JS实现打字机效果

发表于: 2024-08-04 21:07:10

简介: 使用JS实现类似于GPT页面打字机效果

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 存放文字的DOM -->
    <div id="strDom"></div>

</body>

</html>

<script>
    const strDom = document.querySelector('#strDom')
    const str = '我是一个打字机demo'

    // 传入DOM、书写的字符串、打字速度
    function setElementText(strDOM, str, speed) {
        let i = 0
        let textTimer
        function set() {
            if (i < str.length) {
                strDOM.innerHTML = `${str.slice(0, i++)}_`
            }
            else {
                strDOM.innerHTML = str
                clearInterval(textTimer)
            }

            if (!textTimer) {
                textTimer = setInterval(set, speed)
            }
        }

        set()
    }

    setElementText(strDom, str, 120)
</script>

最后更新于:2024-08-04 21:07:10