通过js来实现打字效果

有时候浏览网页经常会看见一些页面出现一些打字的效果,那么是怎么实现的呢?

逻辑

  • 确定目标容器,在哪个容器进行输出
  • 确定输出内容,当前直接根据目标容器确定输出内容即可
  • 需要控制输出频率,因此需要循环输出
  • 完毕

代码

var typper = function( selector, timemin ){
    //默认频率时长75ms
    timemin = timemin || 75;
    //确定容器以及输出内容和当前进度
    var $ele = $(selector),str = $ele.html(),progress = 0;
    //清空内容
    $ele.html('');
    //定时器
    var typertimer = setInterval(function() {
        //根据进度获得当前内容
        var current = str.substr(progress, 1);
        //判断是否是html标签
        if (current == '<') progress='str.indexOf(''>', progress) + 1;
        } else {
            progress++;
        }
        //打印标签和内容
        $ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
        if (progress >= str.length) {
            if($ele.html().endWith('_')){
                $ele.html($ele.html().substring(0,$ele.html().length -1));
            }
            //结束定时器
            clearInterval(typertimer);
        }
    }, timemin);
};

使用

typper('body');

效果


效果图


转载请注明出处:
https://chrunlee.cn/article/js-typper.html