仿chatgpt光标自动移动到文本最后效果

概述

首先我们拿到这样一个需求的时候,首先可能想到的是通过伪元素来实现。但是如果这个文本是富文本,里面包含其他的标签,那就不太好实现了。

解决方法

  • 找到元素内容的最后一个文本节点
  • 在文本节点最后添加一个临时的文字
  • 获取最后一个文字相对视口的位置
  • 计算出相对文本实际位置,把实际位置给到光标
  • 移除临时位置光标

代码实现

既然上面已经有了思路,下面我们实际代码实现一下

样式和html代码

html 复制代码
<!DOCTYPE html>

<html lang="en">

  


<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

  


<style type="text/css">

.text-container {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;

}

.text {
    width: 80%;
    height: 400px;
}

// 光标
.cursor {
    position: absolute;
    width: 5px;
    height: 5px;
    background-color: red;
}

</style>

</head>

<body>
    <div class="text-container">
        <div class="text"></div>
        <div class="cursor"></div>
    </div>
    <script src="./common.js"></script>
</body>

</html>

获取元素

js 复制代码
const textContainer = document.querySelector('.text-container')
// 文本内容
const textElem = document.querySelector('.text')
// 光标
const cursor = document.querySelector('.cursor')

自动添加文本

js 复制代码
async function autoAppend() {

function delay(interval) {
    return new Promise(resolve => setTimeout(resolve, interval));
}
const content = `自动添加文本 asdf
    asides萨福;卡拉屎的飞机啊阿斯顿发生阿斯顿发生地方
    卡拉屎的飞机啊阿斯顿发生阿斯顿发生地方卡拉屎的飞机啊阿斯顿发生阿斯顿发生地方
    <span>asdf</span>
    卡拉屎的飞机啊阿斯顿发生阿斯顿发生wei
`

for (let i = 0; i < content.length; i++) {
    let text = content.slice(0, i);
    //let result = tranformText(text);
    textElem.innerHTML = text;
    updateCursor()
    await delay(300)
    
  }

}

获取最后一个文本节点

js 复制代码
function getLastTextNode(node) {
    if (node.nodeType === Node.TEXT_NODE) {
        return node;
    }
    let childNodes = node.childNodes;
    for (let i = childNodes.length - 1; i >= 0; i--) {
        let lastTextNode = getLastTextNode(childNodes[i]);
        if (lastTextNode) {
            return lastTextNode;
        }
    }
    return null;
}

获取光标位置

js 复制代码
function updateCursor() {

    // 找到最后一个文本节点
    const lastTextNode = getLastTextNode(textElem);
    // 在最后一个文本节点加文字
    const tempNode = document.createTextNode('|');

    if (lastTextNode) {
        lastTextNode.parentNode.insertBefore(tempNode, lastTextNode.nextSibling);
    }else{
        textElem.appendChild(tempNode);
    }
    //根据文本节点设置光标位置
    const range = document.createRange();
    //选中文本对象
    range.setStart(tempNode, 0);
    range.setEnd(tempNode, 0);

    // 获取相对视口位置
    const rect = range.getBoundingClientRect();
    // 获取容器相对视口位置
    const containerRect = textElem.getBoundingClientRect();

    const x = rect.left - containerRect.left;
    const y = rect.top - containerRect.top + 10;

    cursor.style.transform = `translate(${x}px, ${y}px)`;

    tempNode.remove();
}
相关推荐
上山打牛1 分钟前
cornerstone3D 通过二进制渲染影像
前端
华仔啊1 分钟前
GitHub 25k Star!这款开源录屏工具,免费无水印可商用,彻底告别付费
javascript
一只小阿乐6 分钟前
react路由中使用context
前端·javascript·react.js·context 上下文
Hilaku6 分钟前
一周狂揽40K+ Star⭐ 的 Pretext 到底有多变态?
前端·javascript·html
前端郭德纲7 分钟前
JavaScript 原型相关属性详解
开发语言·javascript·原型模式
533_7 分钟前
适用于vue3的拖拽插件:vue-draggable-plus, vuedraggable@next
javascript·vue.js
Southern Wind9 分钟前
AI Skill Server 动态技能中台
前端·后端·mysql·node.js
锦木烁光30 分钟前
多端项目太乱?我是这样用 Monorepo 重构的
前端·架构
早點睡39031 分钟前
ReactNative项目OpenHarmony三方库集成实战:react-native-shadow-2
javascript·react native·react.js
上山打牛34 分钟前
cornerstone3D基本使用
前端