CSS实现前端小组件随笔

发布于:2024-06-20 ⋅ 阅读:(127) ⋅ 点赞:(0)

一.CSS+JS实现打字机效果

1.1实现效果

1.2HTML部分

<span class="bottom-text"></span>

1.3CSS部分

.bottom-text {
    font-fanmily: "fangsong";
    display:inline-block;
    position:relative;
    font-size:20px;
    height:20px;
    inline-height:20px;
    color:white;
}

.bottom-text::after {
    content:"";
    position:absolute;
    right:-10px;
    top:5px;
    height:20px;
    width:2px;
    background-color:#fff;
    //指针动画效果
    animation: san 0.5s steps(1) infinite;
}
@keyframes san{
    0%,100% {
        background-color:#fff;
       }
       50% {
            background-color:transparent;
       }
}

1.4JS部分

    <script>
        //页面底部打字机效果
        const text = document.querySelector(".bottom-text");
        //需要轮替的文本内容列表
        const txt = ["你不比任何人差。","答案在风中飘荡。"];
        //当前文本内容的字符下标
        var crIndex = 0;
        //文本内容列表的下标
        var txtIndex = 0;
        //用来确定是打字还是删字,true是打字,false是删字
        var switchMode = true;
        setInterval(function(){
            if(switchMode) {
                text.innerHTML = txt[txtIndex].slice(0,++crIndex);
            }
            else {
                text.innerHTML = txt[txtIndex].slice(0,crIndex);
                crIndex--;
            }

            //+3是为了打完全部字后停留一段时间,更好的交互效果
            if(crIndex == txt[txtIndex].length+3) {
                switchMode = false;
            }
            //当前文本内容被删光后,进行下一个文本内容的打字
            else if (crIndex < 0) {
                crIndex = 0;
                switchMode = true;
                txtIndex++;
                if(txtIndex >= txt.length){
                    txtIndex = 0;
                }
            }
        //200ms表示打字的快慢,越低打字越快
        },200);
    </script>


网站公告

今日签到

点亮在社区的每一天
去签到