我有这个结构(可以更复杂/包含嵌套标签)
<div id="editor">
<p>Some <i>text</i>
<p>Some other text</p>
</div>
我正在使用
editor.innerText
提取屏幕上可见的文本我得到:
一些文字
其他一些文字
我的后端服务分析此文本并用“位置”为我提供亮点。对于上面的示例,假设它返回 (0,9),这意味着 start 是包含“Some”的文本节点,而 end 节点是包含“text”的节点。如何通过给定位置定位这些节点?
我在使用 DOM 遍历收集文本和跟踪位置方面取得了一些成功,但我丢失了换行符和一些空格(由于
textContent
)。
最佳答案
这个问题的答案不是微不足道的。
最好的解决方案是通过 innerHtml
到您的后端服务以正确突出显示文本,并且它需要能够解析 HTML。
但是,您的其他解决方案是通过您的 innerText
到后端,然后遍历 innerHtml
中的所有字符并忽略尖括号内的所有字符。
这可能需要对空白进行一些清理,以及对 HTML 进行一些修改,但我将把这些留给你。
这是我的意思的一个例子
let searchHtml = "<p>Some <i>text</i><p>Some other text</p>";
let outputHtml = "";
let highlightOpenTag = "<b>";
let highlightCloseTag = "</b>";
let currentlyHighlighting = false;
// Start and end positions from your backend
let startIndex = 0;
let endIndex = 9;
let inTag = false;
let textIndex = 0;
for (let i = 0; i < searchHtml.length; i++) {
let char = searchHtml[i];
// We don't want to insert highlight tags when we're inside a tag already
if (char === '<') inTag = true;
if (inTag) {
outputHtml += char;
} else {
// If we're not in a tag, but we are within the text positions
// returned from the backend, let's get highlighting
if (textIndex >= startIndex && textIndex < endIndex) {
if (!currentlyHighlighting) {
outputHtml += highlightOpenTag;
currentlyHighlighting = true;
}
}
outputHtml += char;
// If we're about to hit a tag and we're already highlighting then
// insert our end highlight tag
if((searchHtml.length < i+1 || searchHtml[i+1]) === '<' && currentlyHighlighting) {
outputHtml += highlightCloseTag;
currentlyHighlighting = false;
}
textIndex++;
}
if (char === '>') inTag = false;
}
console.log(outputHtml);
关于javascript - 按字符位置定位节点(相对于 innerText 的位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61449886/