实现一个打印机效果,给你思路,有优化空间

46 阅读1分钟

所谓的文章加一些特效,能想到的就是打印机动效了。然后记录一下整个实现过程,还是比较简单的。

该代码尚且有优化的空间... 加油


<template>
    <article id="typewriter"></article>
</template>

<script setup>
import { defineComponent, ref, onMounted } from 'vue';


const artical = [
  {
    text: '星期天',
    className: 's1',
  },
  {
    text: '逛公园',
    className: 's2',
  },
  {
    text: '什么园',
    className: 's1',
  },
  {
    text: '性别园',
    className: 's2'
  },
  {
    text: '男性、女性',
    className: 's1'
  }
]

onMounted(() => {
  const typewriterElement = document.getElementById('typewriter');
  let currentIndex = 0;
  let currentCharIndex = 0;

  function type() {
    if (currentIndex >= artical.length) {
      return;
    }

    const currentText = artical[currentIndex].text;
    const currentClassName = artical[currentIndex].className;

    if (currentCharIndex < currentText.length) {
      const span = document.createElement('span');
      span.classList.add(currentClassName);
      span.textContent = currentText[currentCharIndex];
      typewriterElement.appendChild(span);
      currentCharIndex++;
    } else {
      currentIndex++;
      currentCharIndex = 0;
      // typewriterElement.appendChild(document.createElement('br'));
    }
    setTimeout(type, 100);
  }
  type();

})




</script>

<style lang="scss">
.count {
  color: red;
}
.s2 {
  color: #000 !important;
}

.s1  {
  color: #F8C875 !important;
}
</style>