简体   繁体   中英

How to get range of selected text in numbers in javascript?

I have looked at this question and many similar answers but they aren't useful to me, because they give plain text of selected section.I want to get index of start & end points based on parent Node not its children.

For example given the following snippet:

<p>
    hello,
    <span> i </span>
    am 
    <span> here </span>
</p>

I want to select "i am he" and get these numbers : [7,14] which 7 is index of 'i' and 14 is index of 'e' in "hello,i am here" .

when I get selected text by document.getSelection() , start point is 0 & end point is 1(because of span tags.) how can I get start and end points just based on <p> tag (not <p> & <span> s ) and in numerical form?

HTML:

<p>hello,<span> i </span>am<span> here </span></p>

JS:

// Using mouseup to detect the selection (just for test)

window.addEventListener('mouseup', e => {
  let sel = window.getSelection();
  let p = document.querySelector('p'); // THE ELEMENT TAKEN MANUALY!!!

  console.log(findRangeOfSel(p, sel)); // THE RANGE

});

// function to get the range by getting anchor and focus of selection

function findRangeOfSel(el, sel){
    let range = [];
  range[0] = findIndexOfSymbol(el, sel.focusNode, sel.focusOffset);
  range[1] = findIndexOfSymbol(el, sel.anchorNode, sel.anchorOffset);
  range.sort((a,b) => a - b); //rtl or ltr selection gives same result
  return range;
}

// function to get offset from the start of el
function findIndexOfSymbol(el, node, offset){
    node = node.parentNode == el ? node : node.parentNode;
    let nodes = [...el.childNodes];
  let index = nodes.indexOf(node);
  let num = 0;
  for (let i=0; i < index; i++){
    num += nodes[i].textContent.length;
  }
  return num + offset;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM