本篇內容介紹了“在Vue中怎么實現打字機的效果”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
I‘m ByPunk!I‘m looking for a job.I‘m a front-end programmer.I‘m coding the web…
以上四句話循環重復,以打字機的效果顯示輸入和刪除,因為前面的I‘m是相同的,所以只對后面的內容加以修改。
1.事先定義好字符串str:str='By Punk!',使用數組的splite方法將str分解成由字母組成的數組。
2.利用for循環,每100毫秒向數組里push一個新的字母,利用vue的雙向綁定,數據更新帶動視圖更新。
3.在容納字母的div后寫一個豎杠“|”并加上不斷閃爍的動畫,模擬打字機光標。
4.在每次push的時候,判斷當前的索引i是否是數組的最后一個元素,如果是,則在2秒后開始清除。
5.“刪除”具體實現跟“輸入”剛好相反,每200毫秒從數組從pop出最后一項。
6.使用watch鉤子函數實現四句話的循環重復。
<template> <div class="typer"> <div class="typer-content"> <p class="typer-static">I'm </p> <!-- 動態變化的內容--> <p class="typer-dynamic"> <span class="cut"> <span class="word" v-for="(letter,index) in words" :key="index">{{letter}}</span> </span> <!-- 模擬光標--> <span class="typer-cursor"></span> </p> </div> </div> </template>
<script> export default { data () { return { words:[], //字母數組push,pop的載體 str:"By Punk", //str初始化 letters:[], //str分解后的字母數組 order:1, //表示當前是第幾句話 } }, watch:{ //監聽order值的變化,改變str的內容 order(old,newV){ if(this.order%4==1){ this.str="By Punk!" } else if(this.order%4==2){ this.str="looking for a job. " } else if(this.order%4==3){ this.str="a front-end programmer." } else{ this.str="coding the web..." } } }, mounted(){ //頁面初次加載后調用begin()開始動畫 this.begin() }, methods:{ //開始輸入的效果動畫 begin(){ this.letters=this.str.split("") for(var i=0;i<this.letters.length;i++){ setTimeout(this.write(i),i*100); } }, //開始刪除的效果動畫 back(){ let L=this.letters.length; for(var i=0;i<L;i++){ setTimeout(this.wipe(i),i*50); } }, //輸入字母 write(i){ return ()=>{ let L=this.letters.length; this.words.push(this.letters[i]); let that=this; /*如果輸入完畢,在2s后開始刪除*/ if(i==L-1){ setTimeout(function(){ that.back(); },2000); } } }, //擦掉(刪除)字母 wipe(i){ return ()=>{ this.words.pop(this.letters[i]); /*如果刪除完畢,在300ms后開始輸入*/ if(this.words.length==0){ this.order++; let that=this; setTimeout(function(){ that.begin(); },300); } } }, }, } </script>
<style scoped lang="less"> @thePink:#e84d49; .typer{ margin-top: 2%; box-sizing: border-box; } .typer .typer-content{ font-weight: bold; font-size: 50px; display: flex; flex-direction: row; letter-spacing: 2px } .typer-dynamic{ position: relative; } .cut{ color: @thePink; } .typer-cursor{ position: absolute; height: 100%; width: 3px; top: 0; right: -10px; background-color: @thePink; animation: flash 1.5s linear infinite; } </style>
“在Vue中怎么實現打字機的效果”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。