实现文字一个接一个实现

网上冲浪时偶然发现这个文字一个接一个出现的效果,类似于

第一想法,是用css的动画属性,通过控制文字容器的宽度实现。

    //html代码
    <div id="inner">hello from the other side</div>
    //css代码
    #inner {
        background-color: yellow;
        width: 10px;
        height: 25px;
        overflow: hidden;
        word-break: break-all;
        animation: animate 2s infinite;
    }

    @keyframes animate {
        0%{
            width: 0px;
        }
        100%{
            width: 192px;
        }
    }

实现效果:

审查元素之后,发现原网页的文字元素是一个一个添加上去的

这样就可以用JavaScript实现。思路是将文字挨个塞进容器里,再设置定时函数重复运行。

    //html代码
    <div class="container">{<span id="inner"></span>}</div>

    <div id="text">hello from the other side</div>
    //css代码
    .container {
        font-size: 20px;
    }

    #inner {
        background-color: yellow;
        text-align: center;
    }

    #text {
        display: none;
    }
    //js代码
    var index = 0;
        var text = document.getElementById("text").innerText;

        function type() {
            document.getElementById("inner").innerHTML = text.substr(0, index++)
            if (index == text.length) {
                index = 0;
            }
        }

        setInterval(type, 200)

实现效果:

总结来说,JavaScript实现的不如css实现的平滑,会有一种一顿一顿的感觉

猜你喜欢

转载自www.cnblogs.com/dairyDeng/p/11975336.html
今日推荐