随机变速的动态打字特效–最终效果
随机变速的动态打字特效–完整代码
<template> <div class="contentBox"> <span>{{showContent}}</span> <span v-if="showBlinkCursor" class="blinkCursor">|</span> </div> </template> <script> export default { mounted() { let that = this let index = 0; var myFunction = function () { clearInterval(timer); if (index < that.allContent.length) { that.interval = Math.random() * 500 that.showContent += that.allContent[index] index++; timer = setInterval(myFunction, that.interval); } else { that.showBlinkCursor = false } } var timer = setInterval(myFunction, that.interval); }, data() { return { interval: 100, showBlinkCursor: true, showContent: '', allContent: "多想一醒来 晨风就能抚平忧伤\n" + "多想一转身 目光就融化掉冰霜\n" + "多想一抬头 看见你微笑的脸庞\n" + "多想你能够 把喜怒哀乐对我讲\n" + "多想一家人 心朝着同一个方向\n" + "多想一路上 包容着温暖的体谅\n" + "多想一放下 世界就还给你梦想\n" + "多想你知道 爱就在我心底流淌\n" + "生活总该迎着光亮\n" + "再跌跌撞撞也要坚强\n" + "数着流星降落你肩膀\n" + "而我一直陪伴在你身旁\n" + "生活总该迎着光亮\n" + "失望过后拥抱更多希望\n" + "夜的尽头叫做阳光\n" + "手中的幸福 终将会绽放" } } }; </script> <style scoped> .contentBox { white-space: pre-wrap; } .blinkCursor { animation: Blink 1s ease-in 0s infinite; } @keyframes Blink { 0% { opacity: 0; } 100% { opacity: 1; } } </style>
css 闪烁光标
<span class="blinkCursor">|</span>
.blinkCursor { animation: Blink 1s ease-in 0s infinite; } @keyframes Blink { 0% { opacity: 0; } 100% { opacity: 1; } }
js 动态改变setInterval定时器的时间间隔
var interval = 500 var myFunction = function () { // 必须先清除掉定时器,再重新创建定时器,才能改变时间间隔 clearInterval(timer); interval = Math.random() * 500 timer = setInterval(myFunction, interval); } var timer = setInterval(myFunction, interval);