JQ实现打字机效果

目录

一、前言

二、效果图

三、代码


一、前言

本篇博客记录一下基于JQuery实现的打字机效果代码,感兴趣的可以一起学习学习。将下面代码复制到html文件中即可预览效果。

二、效果图

三、代码

<!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>
    <div id="pic" style="display: none;">
        这是一段打字机效果的文字
    </div>
 
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        (function ($) {
            $.fn.typewriter = function () {
                this.each(function () {
                    var $ele = $(this),
                        str = $ele.html(),
                        progress = 0;
                    $ele.html('');
                    var timer = setInterval(function () {
                        var current = str.substr(progress, 1);
                        if (current == '<') {
                            progress = str.indexOf('>', progress) + 1;
                        } else {
                            progress++;
                        }
                        $ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
                        if (progress >= str.length) {
                            clearInterval(timer);
                        }
                    }, 150);
                });
                return this;
            };
        })(jQuery);
 
        $("#pic").show().typewriter(50);
    </script>
</body>
 
</html>
posted @ 2020-07-30 15:04  Wjhsmart  阅读(518)  评论(0编辑  收藏  举报