红叶都枫了 @163

js实现打字机效果(完整实例)

在上篇css高斯模糊的效果基础上用js实现一个打字机效果:

上图:

 

 

 代码:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>js实现打字机效果(高斯模糊背景)</title>
<style>
    .box{
        width: 750px;
        height: 400px;
        background: url('./img/timg.jpg') no-repeat 100% 100%;
        background-size: cover;
        position: relative;
    }
    .content{
        height: 60%;
        width: 60%;
        background: white;
        position: absolute;            
        left: 50%;
        top: 50%;
        margin-left: -30%;
        margin-top: -16%;
        border-radius: 4px;
    }
    /* filter是对该元素的模糊,因此对content添加并模糊伪元素,并定位到content的下层,而不是直接修改背景图或content的样式 */
    .content::before{
        content: '';
        position: absolute;
        top:0;right:0;bottom:0;left:0;
        filter: blur(3px);
        margin:-21px;  
        background: url('./img/timg.jpg') no-repeat 100% 100%;
        background-size: cover;
        opacity: .8;
    }
    .content p{
        padding: 20px 15px;
        color: white;
        text-indent: 20px;
        font-size: 14px;
        line-height: 28px;
        letter-spacing: 1px;
        /* 清除子元素对父元素filter属性值的继承 */
        filter: blur(0);          
    }
</style>
</head>
<body>
    <div class="box">
        <div class="content" id="contents">
        </div>
    </div>
</body>
</html>
<script>
    function start(){
        let str = ' 什么是永远?有生之年就是永远。分手不是一定坏事,只是证明那个人不是你的地久天长。在时间线上,是有一个人在等你,时间到了,就会相遇。<br/>&nbsp;&nbsp;&nbsp;&nbsp;我好像没有特别喜欢的事情,但是和喜欢的朋友一起随便聊聊天,打打游戏 ,花时间做点无聊的事情,就很高兴了,因为和舒服的人一起挥霍时间本身就是很轻松快乐的事情。<br/>--红叶都枫了@163'
        let str_ = ''
        let i = 0
        let content = document.getElementById('contents')
        let timer = setInterval(()=>{
            if(str_.length<str.length){
                str_ += str[i++]
                content.innerHTML = '<p>'+str_+'_</p>'                        //打印时加光标
            }else{ 
                clearInterval(timer)
                content.innerHTML = '<p>'+str_+'</p>'
            }
        },100)
    }
    start()
</script>

 

posted @ 2020-09-09 11:06  红叶都枫了163  阅读(4013)  评论(0编辑  收藏  举报