Vue中实现一个博客打字机效果

Vue中实现一个博客打字机效果

徐徐
前端
发布于2024-08-28 16:21:46
🌺前言
Vue中实现一个博客打字机效果

vue
<template>
  <h3 class="typewriter">
    <span
      ref="textSpan"
      :class="{ typed: isTyped }">
      {{ typedText }}
    </span>
    <span
      v-if="showCursor"
      class="cursor">
      {{ cursor }}
    </span>
  </h3>
</template>
  
<script setup>
import { ref, onMounted } from 'vue';
const  props = defineProps({
  text: {
    type: String,
    default: ''
  }
})
const {text} = toRefs(props)
// const text = '每一天都是你改变未来的机会。';
const speed = 100; // 每个字符之间的延迟时间(毫秒)
let index = 0;
const showCursor = ref(true);
const cursor = '|';
const typedText = ref('');
const isTyped = ref(false);
const textSpan = ref();
let timer1 = null
let timer2 = null
let timer3 = null
// 无限循环的打字效果
const loopTypeWriter =() => {
  if (index < text.value.length) {
    typedText.value += text.value.charAt(index);
    index++;
    timer1 =setTimeout(() => {
      clearTimeout(timer1)
      loopTypeWriter();
    }, speed);
  } else {
    // 当所有字符都已打印后,清除已打印的文本并重新开始
    timer2 =setTimeout(() => {
      typedText.value = '';
      index = 0;
      clearTimeout(timer2)
      timer3= setTimeout(() => {
        clearTimeout(timer3)
        loopTypeWriter();
      },2000)
       
    }, 2000); // 停顿2秒后再重新开始
  }
}
  
onMounted(() => {
  loopTypeWriter();
});
onBeforeUnmount(() => {
  timer1&&clearTimeout(timer1)
  timer2&&clearTimeout(timer2)
  timer3&&clearTimeout(timer3)
})

</script>
  
  <style scoped>
  .typewriter {
    font-family: monospace;
    font-size: 24px;
    white-space: nowrap;
    overflow: hidden;
    background-color: rgba(0,0,0,0.5);
    cursor: pointer;
    border-radius: 10px;
    color: #fff;
    font-size:20px;
    padding: 15px;
  }
  
  .cursor {
    display: inline-block;
    animation: blink 1s infinite;
  }
  
  @keyframes blink {
    50% {
      opacity: 0;
    }
  }
  
  .typed {
    width: 0;
    overflow: hidden;
    border-right: 2px solid transparent;
    animation: typing 3s steps(40, end), blink-caret 0.75s step-end infinite;
  }
  
  @keyframes typing {
    from {
      width: 0;
    }
    to {
      width: 100%;
    }
  }
  
  @keyframes blink-caret {
    from, to {
      border-color: transparent;
    }
    50% {
      border-color: black;
    }
  }
  </style>
文章最后更新于 2024-08-28 16:21:46
留言
暂无数据

~~空空如也