vue3 css实现文字输出带光标显示,文字输出完毕,光标消失的效果

Vue实现过程如下:

html 复制代码
<template>
  <div >
    <p ref="dom_element" class="typing" :class="{over_fill: record_input_over}"></p>
  </div>
</template>
<script setup>
import {onMounted, ref} from "vue";
const wrap_time_out = ref()
const inner_time_out = ref()
const record_input_over = ref(false)
const dom_element = ref(null)

onMounted(()=>{
  // 也可以通过这种方式实现而不是通过ref
  // const typingElement = document.getElementsByClassName("typing")[0];
  const typingDelay = 50; // 每个字符打印的时间间隔
  const cursorDelay = 500; // 光标闪烁的时间间隔
  const text = "This is an example of typing animation.";
  function type_my() {
    // 计算出应该打印的文本
    const currentText  = text.slice(0, typingIndex);
    // 更新显示的文本和光标位置
    // typingElement.textContent = currentText;
    dom_element.value.textContent = currentText;

    // 如果还没打印完所有文本,则继续打印
    if (typingIndex < text.length) {
      typingIndex++;
      inner_time_out.value = setTimeout(type_my, typingDelay);
    }else {
      // 清除 定时器
      clearTimeout(wrap_time_out.value)
      clearTimeout(inner_time_out.value)
      // 当输入完成后通过控制样式将光标清除
      record_input_over.value = true
    }
  }
  let typingIndex = 0;

// 等待一段时间,让用户有时间看到光标
  wrap_time_out.value = setTimeout(type_my, cursorDelay);
})

</script>

<style >
html, body{
  height: 100%;
  width: 100%;
  //background-color: pink;
}

.typing {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  font-size: 24px;
  line-height: 1.5;
}
.typing::after{
  content: '|';
  animation: blink 0.8s infinite;
  padding-left: 5px;
}
.over_fill::after{
  content: "";
  animation: none;
  padding-left: 0;
}
@keyframes blink {
  50% {
    opacity: 0;
  }
}
</style>

效果如下:


输入完成则光标消失,效果如下:

相关推荐
哆啦A梦1588几秒前
Element-Plus
前端·vue.js·ts
IT_陈寒7 分钟前
🔥3分钟掌握JavaScript性能优化:从V8引擎原理到5个实战提速技巧
前端·人工智能·后端
前端小巷子30 分钟前
JS 打造丝滑手风琴
前端·javascript·面试
Mintopia42 分钟前
多模态 AIGC 在 Web 内容创作中的技术融合实践:把“创作引擎”装进浏览器
前端·javascript·aigc
鹏多多.1 小时前
flutter-使用fluttertoast制作丰富的高颜值toast
android·前端·flutter·ios
Mintopia1 小时前
Next.js 的 Web Vitals 监测与 Lighthouse 分析:从底层到实战的快乐科学
前端·javascript·next.js
charlie1145141911 小时前
前端三件套简单学习:HTML篇1
开发语言·前端·学习·html
很多石头1 小时前
前端img与background-image渲染图片对H5页面性能的影响
前端·css
yenggd1 小时前
3种XSS攻击简单案例
前端·xss
盖头盖1 小时前
【xss基本介绍】
前端·xss