js+css实现打字机效果(大模型网页常用)

在大模型网站,经常能看见类似下图的打字机效果,这是我做的一个示例:
在这里插入图片描述
如何做出来呢?这个示例里,打字机的效果用js函数实现,文字最后的闪烁光标是span并修改样式来实现。代码如下:

/**
 * 实现打字机效果的函数(不含最后的光标,光标需要自己用css实现)
 * @param container 接收当前显示内容的对象
 * @param content 要展示的完整一段话内容
 * @param typeIntervalTime 间隔多久打出一个字(毫秒,下同)
 * @param restTime 当内容打印完成后,等待多久后重新打印(为负数则不再重新打印)
 */
export function typewriterEffect(container: Ref<string>, content: string, typeIntervalTime: number = 160, restTime: number = 3200) {
  let index = 0
  let temp = setInterval(() => {
    container.value += content.at(index)
    index++
    if (index === content.length) {
      clearInterval(temp)
      if (restTime >= 0) {
        setTimeout(() => {
          container.value = ''
          typewriterEffect(container, content)
        }, restTime)
      }
    }
  }, typeIntervalTime)
}

// 大模型字符输入内容
const text1 = '我是Kimi,是月之暗面开发的大模型哟!'
const titleText = ref<string>('')
typewriterEffect(titleText, text1)
<div id="title">
  <span id="text-span" v-html="titleText"></span>
  <span id="cursor-span"></span>
</div>
#title {
   position: absolute;
   top: 220px;
   left: 50%;
   transform: translateX(-50%);
   width: 800px;

   font-family: Microsoft YaHei;
   font-size: 24px;
   font-weight: 550;
   line-height: 150%;
   text-align: center;
   letter-spacing: 0em;
   color: #3D3D3D;

   #text-span {
     display: inline-block;
   }

   #cursor-span {
     display: inline-block;
     margin-bottom: -3px;
     margin-left: 2px;
     width: 24px;
     height: 2px;
     background: rgb(79, 159, 255);
     animation: cursorBlink 1s linear infinite;

     @keyframes cursorBlink {
       10% { opacity: 0.9; }
       20% { opacity: 0.8; }
       30% { opacity: 0.7; }
       40% { opacity: 0.6; }
       50% { opacity: 0.5; }
       60% { opacity: 0.4; }
       70% { opacity: 0.3; }
       80% { opacity: 0.2; }
       90% { opacity: 0.1; }
       100% { opacity: 0; }
    }
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值