如何获取lightning-input-rich-text中高亮文本的起止索引并正确替换?
解决lightning-input-rich-text选中文本索引错误与替换异常问题
一、获取全局文本索引(解决多行offset错误)
window.getSelection()返回的offset是相对于当前选中的文本节点的,并非整个富文本内容的全局索引,所以多行场景下会出现索引重置的问题。要拿到全局索引,需要遍历编辑器内所有文本节点,累计计算偏移量:
function getGlobalSelectionIndices() { const editor = document.querySelector('lightning-input-rich-text').shadowRoot.querySelector('.slds-rich-text-editor__textarea'); const selection = window.getSelection(); if (!selection.rangeCount) return { start: -1, end: -1 }; const range = selection.getRangeAt(0); let startIndex = 0; let endIndex = 0; // 遍历文本节点计算起始位置 const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, null, false); let node; while (node = walker.nextNode()) { if (node === range.startContainer) { startIndex += range.startOffset; break; } startIndex += node.textContent.length; } // 重置遍历器计算结束位置 walker.currentNode = editor; while (node = walker.nextNode()) { if (node === range.endContainer) { endIndex += range.endOffset; break; } endIndex += node.textContent.length; } // 处理反向选中的情况 if (startIndex > endIndex) [startIndex, endIndex] = [endIndex, startIndex]; return { start: startIndex, end: endIndex }; }
调用该函数即可获取整个富文本内容的全局起始/结束索引,不受选中行位置影响。
二、正确替换选中内容(避免自动添加换行)
直接操作DOM的deleteContents()和insertNode()会破坏编辑器内部结构,导致自动补全换行。推荐利用组件自身的value属性结合全局索引替换:
function replaceSelectedText(replacementText) { const richText = document.querySelector('lightning-input-rich-text'); const { start, end } = getGlobalSelectionIndices(); if (start === -1 || end === -1) return; // 获取当前内容并替换选中部分 const currentValue = richText.value; const newValue = currentValue.substring(0, start) + replacementText + currentValue.substring(end); // 回写内容到编辑器 richText.value = newValue; }
如果需要保留HTML格式,直接操作HTML字符串即可,注意处理标签闭合逻辑。
也可以使用编辑器兼容的execCommand方法,自动适配内部结构:
const editor = document.querySelector('lightning-input-rich-text').shadowRoot.querySelector('.slds-rich-text-editor__textarea'); editor.focus(); document.execCommand('insertText', false, 'Hello');
内容的提问来源于stack exchange,提问作者User2529
相关产品推荐
相关产品推荐

