uniapp的光标跟随和打字机效果

1、准备好容器

文字的显示textRef,以及光标的显示 ,使用transform-translate对光标进行移动到文字后面

2、准备样式

样式,你可以自定义,不必安装我的,主要是光标的闪烁动画


 3、逻辑

1、模拟接受数据
      async mockResponse() {
        this.cursorShow = true;
        for (let i = 0; i < this.nodeData.length; i++) {
          try {
            this.nodeText = this.nodeData.slice(0, i);
            this.updateCursor();
            await this.delay(100);
          } catch (e) {
            console.log(e)
          }
        }
        this.cursorShow = false;
      },
2、更新光标位置
      updateCursor() {
        // 1. 找到最后一个文本节点
        const lastTextNode = this.getLastTextNode(this.$refs.textRef,1);
        // 2. 创建一个临时文本节点
        const tempText = document.createTextNode('\u200B'); // 零宽字符
        // 3. 将临时文本节点放在最后一个文本节点之后
        if (lastTextNode) {
          lastTextNode.parentNode && lastTextNode.parentNode.appendChild(tempText);
        } else {
          this.$refs.textRef && this.$refs.textRef.$el.appendChild(tempText);
        }
        // // 4. 获取临时文本节点距离父节点的距离(x,y) 可以使用 setStart 和 setEnd 方法来设置 Range 的开始和结束位置。
        const range = document.createRange(); // 设置范围
        range.setStart(tempText, 0);
        range.setEnd(tempText, 0);
        const rect = range.getBoundingClientRect(); // 获取距离信息
        // // 5. 获取当前文本容器距离视图的距离(x,y)
        const textRect = this.$refs.contentRef && this.$refs.contentRef.$el.getBoundingClientRect();
        // 6. 获取到当前文本节点的位置,并将光标的位置插入到相应位置
        if (textRect) {
          const x = rect.left - textRect.left + 10;
          const y = rect.top - textRect.top; // 7.5 是光标高度的一半,为了居中显示光标
          this.x = x;
          this.y = y;
        }
        // 7. 移除临时文本节点
        tempText.remove();
      },

4、完整代码 如下:





你可能感兴趣的:(uniapp,uni-app,javascript,前端)