这个脚本现在有个问题。是按换行\n来分辨行数的,但是我有的一条长文字后面只有一个\n, 看上去这条长文字会占2行以上, 那这个back-div的移动距离就定位不准确了: // 跟随textarea中光标位置移动的绿色小背景条

const bgDiv = document.querySelector('#back-div');
const lineHeight = parseInt(getComputedStyle(deepLTextArea).lineHeight); // 获取行高

function moveDeepLBgDiv() {
    const text = deepLTextArea.value;
    const cursorPos = deepLTextArea.selectionStart; // 获取光标位置
    const textBeforeCursor = text.substring(0, cursorPos); // 获取光标前的文本
    const lines = textBeforeCursor.split('\\n'); // 将光标前文本按行分割成数组
    const currentLine = lines.length - 1; // 光标所在行的行号(从零开始)
    const top = currentLine * lineHeight + 50; // 计算背景div的top值,加上2个像素的偏移量,使其不至于挡住光标
    bgDiv.style.top = `${top}px`;
    bgDiv.style.display = 'block';
}


function hideBgDiv() {
    bgDiv.style.display = 'none';
}

deepLTextArea.addEventListener('click', moveDeepLBgDiv);
deepLTextArea.addEventListener('keyup', moveDeepLBgDiv);
deepLTextArea.addEventListener('blur', hideBgDiv);

可以考虑使用正则表达式来匹配行数,例如将换行符\n和回车符\r都作为分隔符,然后再将连续的分隔符视为一个分隔符,这样就可以避免长文字占用多行的问题。修改代码如下:

const lines = textBeforeCursor.split(/[

]+/g); // 将光标前文本按行分割成数组,支持换行符和回车符
const currentLine = lines.length - 1; // 光标所在行的行号(从零开始)
const top = currentLine * lineHeight + 50; // 计算背景div的top值,加上2个像素的偏移量,使其不至于挡住光标

这样就可以正确计算出行数,确保背景div的移动距离正确。

使用正则表达式解决 textarea 光标位置背景条定位不准确问题

原文地址: https://www.cveoy.top/t/topic/oo6Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录