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>

效果如下:


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

相关推荐
没有bug.的程序员4 分钟前
Spring Boot Actuator 监控机制解析
java·前端·spring boot·spring·源码
DarkBule_8 分钟前
0成本get可信域名:dpdns.org公益域名获取全攻略
css·学习·html·github·html5
包饭厅咸鱼25 分钟前
autojs----2025淘宝淘金币跳一跳自动化
java·javascript·自动化
OpenTiny社区35 分钟前
如何使用 TinyEditor 快速部署一个协同编辑器
前端·开源·编辑器·opentiny
IT_陈寒39 分钟前
震惊!我用JavaScript实现了Excel的这5个核心功能,同事直呼内行!
前端·人工智能·后端
前端伪大叔1 小时前
freqtrade智能挂单策略,让你的资金利用率提升 50%+
前端·javascript·后端
江城开朗的豌豆1 小时前
从“any”战士到类型高手:我的TypeScript进阶心得
前端·javascript·前端框架
红尘散仙1 小时前
TRNovel王者归来:让小说阅读"声"临其境的终端神器
前端·rust·ui kit
知花实央l1 小时前
【Web应用安全】SQLmap实战DVWA SQL注入(从环境搭建到爆库,完整步骤+命令解读)
前端·经验分享·sql·学习·安全·1024程序员节
烛阴1 小时前
为你的Lua代码穿上盔甲:精通错误处理的艺术
前端·lua