仿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();
}
相关推荐
speedoooo10 分钟前
在现有App里嵌入一个AI协作者
前端·ui·小程序·前端框架·web app
全栈胖叔叔-瓜州21 分钟前
关于llamasharp 大模型多轮对话,模型对话无法终止,或者输出角色标识User:,或者System等角色标识问题。
前端·人工智能
三七吃山漆29 分钟前
攻防世界——wife_wife
前端·javascript·web安全·网络安全·ctf
用户479492835691532 分钟前
面试官问"try-catch影响性能吗",我用数据打脸
前端·javascript·面试
GISer_Jing1 小时前
前端营销技术实战:数据+AI实战指南
前端·javascript·人工智能
GIS之路1 小时前
使用命令行工具 ogr2ogr 将 CSV 转换为 Shp 数据(二)
前端
嘉琪0011 小时前
Vue3+JS 高级前端面试题
开发语言·前端·javascript
vipbic2 小时前
用 Turborepo 打造 Strapi 插件开发的极速全栈体验
前端·javascript
天涯学馆2 小时前
为什么 JavaScript 可以单线程却能处理异步?
前端·javascript
Henry_Lau6173 小时前
主流IDE常用快捷键对照
前端·css·ide