打字机文字效果(vue2版本)

打字机文字效果

示例图片

在这里插入图片描述

示例组件代码

<template>
  <div id="text-typing">
    <pre class="textClass">{{ displayText }}<span class="cursor">|</span></pre>
  </div>
</template>

<script>
export default {
  props: {
    lines: {
      type: Array,
      default() {
        return ['希望广大老年朋友保持老骥伏枥、老当益壮的健康心态和进取精神,既要老有所养、老有所乐,又要老有所为,为推进中国式现代化贡献‘银发力量’。','近日给“银龄行动”老年志愿者代表回信,并祝全国老年朋友们健康长寿、生活幸福。'];
      },
    },
    timeNum: {
      type: Number,
      default: 100, // 默认打字速度为100ms
    },
  },
  data() {
    return {
      displayText: '',
      currentLineIndex: 0,
      currentCharIndex: 0,
      typingInterval: null,
    };
  },
  methods: {
    typeLine() {
      if (this.currentCharIndex < this.lines[this.currentLineIndex].length) {
        // 逐字显示当前行的文本
        this.displayText +=
          this.lines[this.currentLineIndex][this.currentCharIndex];
        this.currentCharIndex++;
      } else {
        // 当前行显示完毕,准备显示下一行
        if (this.currentLineIndex + 1 < this.lines.length) {
          this.displayText += '\n'; // 添加换行符
        }
        this.currentLineIndex++;
        this.currentCharIndex = 0;
        if (this.currentLineIndex >= this.lines.length) {
          // 所有行显示完毕,重置并重新开始
          this.currentLineIndex = 0;
          clearInterval(this.typingInterval); // 清除定时器
          // setTimeout(this.startTyping, 5000); // 等待5秒后重新开始
        }
      }
    },
    startTyping() {
      // 清空显示文本,重新开始
      this.displayText = '';
      if (this.typingInterval) {
        clearInterval(this.typingInterval);
      }
      this.typingInterval = setInterval(this.typeLine, this.timeNum); //这里调整打字速度
    },
  },
  mounted() {
    if (this.lines.length > 0) {
      this.startTyping();
    }
  },
  beforeDestroy() {
    clearInterval(this.typingInterval); // 组件销毁前清除定时器
  },
};
</script>

<style>
.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
.textClass {
  font-family: Arial, sans-serif;
  font-size: 16px;
  line-height: 30px;
  color: #333;
  white-space: break-spaces;
  word-wrap: break-word;
  text-align: left;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值