首頁  >  問答  >  主體

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 天前488

全部回覆(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
  • 取消回覆