微信小程序如何实现类似于chatGpt的打印机效果
发布于 1 年前 作者 dujie 1895 次浏览 来自 分享

背景:最近的chatGpt类的应用十分火爆。Gpt官网有个输入的效果。作为前端开发如何实现这种交互。

  1. 利用js实现。
renderContent(item: MsgType, number) {
    const that = this;
    // showContent 是逐渐显示的内容。content是完整的显示内容。
    function typing() {
      if (item.showContent && item?.showContent?.length < item.content.length) {
        // 每次需要截取的步长。步长加一。
        let index = item.showContent.length + 1
        item.showContent = item.content.substring(0, index);
        item.timer = setTimeout(typing, 100);
      } else {
        item.showContent = item.content;
        item.timer && clearTimeout(item.timer);
      }
      that.setData({
        [`msgList[${number}].showContent`]: item.showContent,
        [`msgList[${number}].timer`]: item.timer,
      });
    }
    typing();
  }
2.	利用css实现。

	wxml的代码
  <view class="typing">简易中文打字效果</view>

 

WXSS的效果
.typing {
    width: 15em;
    white-space: nowrap;
    border-right: 2px solid transparent;
    animation: typing 3.5s steps(15, end), blink-caret .75s step-end infinite;
    overflow: hidden;
}
/* 打印效果 */
[@keyframes](/user/keyframes) typing {
  from { width: 0; }
  to { width: 15em; }
}
/* 光标闪啊闪 */
[@keyframes](/user/keyframes) blink-caret {
  from, to { box-shadow: 1px 0 0 0 transparent; }
  50% { box-shadow: 1px 0 0 0; }
}
回到顶部