如何获取div的多行文本中选定文本的起始索引?

问题描述 投票:0回答:1

假设我有一个可编辑的 div,其中包含以下几行:

enter image description here

如何检索文本中“w”的位置?

我无法使用:

window.getSelection().anchorOffset;

因为这获取的是行中的位置,而不是文本中的位置,即 0 而不是 5。

我不想使用:

element.innerText.indexOf(selectedText);

因为它可能会检索相似的文本。

javascript html offset
1个回答
0
投票

您的锚点偏移量应为 6。

索引 性格
0 H
1 e
2 l
3 l
4 o
5
6 w <- Here
7 o
8 r
9 l
10 d

const el = document.querySelector('#test');
const btn = document.querySelector('#btn');

selectText(el, 'w');
btn.dispatchEvent(new MouseEvent('click')); // 6

function getPos(event) {
  console.log(window.getSelection().anchorOffset);
}

function selectText(el, text) {
  const content = el.textContent;
  const startIndex = content.indexOf(text);
  if (startIndex === -1) return;
  const endIndex = startIndex + text.length;
  selectTextRange(el, startIndex, endIndex);
}

function selectTextRange(el, startIndex, endIndex) {
  const textNode = el.firstChild;
  const selection = window.getSelection();
  const range = document.createRange();
  range.setStart(textNode, startIndex);
  range.setEnd(textNode, endIndex);
  selection.removeAllRanges();
  selection.addRange(range);
}
<div id="test" style="white-space:pre;" contenteditable>Hello
world</div>
<br>
<button id="btn" onClick="getPos(event)">Get Selection</button>

© www.soinside.com 2019 - 2024. All rights reserved.