jQuery实现打字机效果

效果展示入口:https://skyfood.github.io/typewriter/demo.html

html代码:

<div id="oDiv">
    <p>又回到春末的五月</p>
    <p>凌晨的集市人不多</p>
    <p>小孩在门前唱着歌</p>
    <p>阳光它照暖了溪河</p>
    <p>柳絮乘着大风吹</p>
    <p>树影下的人想睡</p>
    <p>沉默的人 从此刻</p>
    <p>开始快乐起来</p>
    <p>脱掉寒冬的盔垒</p>
    <p>我忧郁的白衬衫</p>
    <p>青春口袋里面的</p>
    <p>第一支香烟</p>
    <p>情窦初开的 我</p>
    <p>从不敢和你说</p>
</div>

css代码:

<style>
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    background: -webkit-linear-gradient(180deg, #1371c6, #61c6f2);
    background: -o-linear-gradient(180deg, #1371c6, #61c6f2);
    background: -moz-linear-gradient(180deg, #1371c6, #61c6f2);
    background: linear-gradient(180deg, #1371c6, #61c6f2);
}
#oDiv {
    width: 300px;
    height: 400px;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}
p {
    font-size: 30px;
    color: #fff;
    display: none;
}
</style>

jQuery代码:

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    //单个p元素显隐
    function showOne(obj, speed) {
        //split() 方法用于把一个字符串分割成字符串数组。
        var texts = obj.html().split(""); 
        //字符串数组中单个字符用于显示的时间  (2/3个speed) / 字符个数
        var s = speed * 2 / 3 / texts.length; 
        obj.html("").show();
        for (var i = 0; i < texts.length; i++) {
            (function (index) {
                setTimeout(function () {
                    obj.append(texts[index]);
                    //如果字符全部显示完成 就隐藏
                    if (index == texts.length - 1) { 
                        //字符串数组中所有字符用于隐藏的时间  1/3个speed
                        obj.fadeOut(speed / 3); 
                    }
                }, s * index); //字符依次显示
            }(i));
        };
    };
    //所有p元素循环
    function showAll(obj, speed) {
        obj.each(function (index, element) {
            setTimeout(function () {
                showOne($(element), speed);
            }, speed * index)
        })
    };
    //定时器 
    function setTimer(obj, speed) {
        showAll(obj, speed);
        return setInterval(function () {
            showAll(obj, speed);
        }, speed * obj.length);
    }

    var p = $("p");
    var speed = 3000;
    setTimer(p, speed);
</script>

涉及知识点:

  1. split(),String 对象方法,用于把一个字符串分割成字符串数组;

  2. 立即执行函数;

  3. setTimeout(),HTML DOM Window 对象方法,用于在指定的毫秒数后调用函数或计算表达式;

  4. append(),jQuery文档操作方法,用于在被选元素的结尾(仍然在内部)插入指定内容;

  5. each(),jQuery遍历方法,语法$(selector).each(function(index,element){});

  6. setInterval(),HTML DOM Window 对象方法,按照指定的周期(以毫秒计)来调用函数或计算表达式。


demo下载地址:https://gitee.com/skyfood/Typewriter.git

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值