首页  >  问答  >  正文

javascript - 用原生js模拟电脑打字效果出了问题,请求大神帮助?

<!--请大神复制黏贴下面的代码,在浏览器运行即可看到问题所在-->
<!DOCTYPE html>
<html>
<head>

<meta charset='utf-8'>
<title>打字机效果</title>
<style> 
#main{ 
    border: 1px solid #ccc;
    height:100px;
    width:1000px;
}
</style>

</head>
<body>
<p id='main'></p>
<script type="text/javascript">
var context='这个程序是想先输逐个出所有文字,三秒钟以后逐个删除所有文字,但是运行以后发现删除到头又会重新删除一遍,请大神帮忙看看,谢谢!'
//console.log(a.length)
var contextLength=Number(0)
var writecontext=document.querySelector('#main')
function loop(){

return new Promise(function(sol,rej){ 
    function lop(){ 
        var t=setTimeout(function(){ 
            if(contextLength<context.length){ 
                writecontext.innerHTML=context.slice(0,contextLength++)+'_'
                lop()
            }
            else{ 
                if(contextLength=context.length){ 
                    setTimeout(function(){ 
                        clearTimeout(t)
                        sol(contextLength)
                    },3000)
                }
            } 
        },200) 
    }
    lop()
})

}

loop().then(function(value){

    function lp(){ 
        var n=setTimeout(function(){ 
            if(value>0){ 
                writecontext.innerHTML=context.slice(0,contextLength--)+'_'
                lp()
            }else{ 
                if(value<=0){ 
                    clearTimeout(n)
                }
            } 

        },50)
    }
    lp()

})
</script>
</body>
</html>

怪我咯怪我咯2711 天前489

全部回复(4)我来回复

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:18:52

    问题出在lp()函数中

    if(value>0){
       writecontext.innerHTML=context.slice(0,contextLength--)+'_'
       lp()
       }else{...}

    此处判断的是value但是操作的是contextLength,所以导致lp()函数死循环。

    解释下删除两次的原因:主要是slice()方法

    'string'.slice(0,n);

    当n是正数时按照正常顺序执行;当n是负数时,执行时n会被替换成字符串长度+n,具体查看MDN。
    所以,第一次执行lop()字符串删除到0之后,contextLength继续减一,导致了视觉上删除了两次

    回复
    0
  • PHP中文网

    PHP中文网2017-05-19 10:18:52

    你写的lp函数其实是无限循环函数来的,需要把lp函数下的contextLength--改为value--,且需要把value > 0改为value >= 0

    回复
    0
  • 某草草

    某草草2017-05-19 10:18:52

    雷雷

    回复
    0
  • 怪我咯

    怪我咯2017-05-19 10:18:52

    把字存成一个数组,然后对数组实现增删

    回复
    0
  • 取消回复