跨节点触发选择文本

function selectText(targetText, container, parentElement) {
  if(typeof parentElement === 'string') parentElement = document.querySelector(parentElement);
  if(typeof container === 'string') container = (parentElement||document).querySelector(container);
  const allText = container.textContent;
  const startGlobalIndex = allText.indexOf(targetText);
  if (startGlobalIndex === -1) return;

  let currentIndex = 0;
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);

  let startNode, startOffset, endNode, endOffset;
  let node;

  while ((node = walker.nextNode())) {
    const nodeLength = node.nodeValue.length;
    // 判断起始位置是否在此节点
    if (currentIndex <= startGlobalIndex && currentIndex + nodeLength > startGlobalIndex) {
      startNode = node;
      startOffset = startGlobalIndex - currentIndex;
    }
    // 判断结束位置是否在此节点
    const endGlobalIndex = startGlobalIndex + targetText.length;
    if (currentIndex <= endGlobalIndex && currentIndex + nodeLength >= endGlobalIndex) {
      endNode = node;
      endOffset = endGlobalIndex - currentIndex;
      break;
    }
    currentIndex += nodeLength;
  }

  if (startNode && endNode) {
    const range = document.createRange();
    range.setStart(startNode, startOffset);
    range.setEnd(endNode, endOffset);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

使用示例

setTimeout(()=>{selectText('fffhgfff333hgggjhjhhhjjj', document.activeElement);openAny.press('meta+b',document.activeElement)}, 4000)

image.png

留下你的脚步
推荐阅读