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>

效果如下:


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

相关推荐
可问 可问春风15 分钟前
JavaScript 性能优化实战指南
开发语言·javascript·性能优化
乆夨(jiuze)16 分钟前
简述下npm,cnpm,yarn和pnpm的区别,以及跟在后面的-g,--save, --save-dev代表着什么
前端·npm·node.js
好_快1 小时前
Lodash源码阅读-baseFindIndex
前端·javascript·源码阅读
好_快1 小时前
Lodash源码阅读-strictIndexOf
前端·javascript·源码阅读
liangshanbo12151 小时前
下载 CSS 文件阻塞,会阻塞构建 DOM 树吗?会阻塞页面的显示吗?
前端·css
Student_Zhang1 小时前
推荐一个数据加密的框架GMObjc(iOS)
前端·算法·github
还是鼠鼠2 小时前
Node.js 模块化概念详细介绍
前端·javascript·vscode·node.js·web
TE-茶叶蛋2 小时前
前端npm包- CropperJS
前端·npm·node.js
正小安2 小时前
前端高阶面试题·每日一题
前端·javascript·面试题
胡桃夹夹子3 小时前
vue 仿deepseek前端开发一个对话界面
前端·javascript·vue.js