JavaScript 实现打字效果


function typing(that)
{
    that = typeof(that.length) == 'undefined' ? [that] : that;

    for(var i = 0; i < that.length; i ++)
    {
        let text = that[i];
        let str = text.innerHTML;
        let index = 0;
        text.innerHTML = '';

        let timer = setInterval(function()
        {
            var current = str.substr(index, 1);
            if(current == '<')
            {
                index = str.indexOf('>', index) + 1;
            }
            else
            {
                index ++ ;
            }

            text.innerHTML = str.substring(0, index) + (index & 1 ? '_': '');

            if(index >= str.length)
            {
                text.innerHTML = str.substring(0, index);
                clearInterval(timer);
            }
        }, 40);
    }
}

typing(document.getElementsByClassName('words1'));
typing(document.getElementById('words2'));

 

posted @ 2022-06-21 15:56  何效名  阅读(144)  评论(0编辑  收藏  举报