Home > Web Front-end > JS Tutorial > body text

How to Get the Start and End Offsets of a Text Selection Within a Container Element?

DDD
Release: 2024-11-17 16:38:01
Original
289 people have browsed it

How to Get the Start and End Offsets of a Text Selection Within a Container Element?

Get the Starting and Ending Positions of a Text Selection Relative to Its Container

Problem:

Consider the following HTML:

<div>
Copy after login

Suppose a user selects the text "home" from this element. How can we determine the start and end offsets of this selection relative to the #parent container?

Answer:

The range.startOffset property appears to provide the desired functionality, but it represents an offset only within the immediate container. Moreover, it only represents a character offset if the container is a text node.

Updated Code:

Here's an updated version of the code that correctly returns both the start and end offsets:

function getSelectionCharacterOffsetWithin(element) {
  var start = 0;
  var end = 0;
  var doc = element.ownerDocument || element.document;
  var win = doc.defaultView || doc.parentWindow;
  var sel;
  if (typeof win.getSelection != "undefined") {
    sel = win.getSelection();
    if (sel.rangeCount > 0) {
      var range = win.getSelection().getRangeAt(0);
      var preCaretRange = range.cloneRange();
      preCaretRange.selectNodeContents(element);
      preCaretRange.setEnd(range.startContainer, range.startOffset);
      start = preCaretRange.toString().length;
      preCaretRange.setEnd(range.endContainer, range.endOffset);
      end = preCaretRange.toString().length;
    }
  } else if ((sel = doc.selection) && sel.type != "Control") {
    var textRange = sel.createRange();
    var preCaretTextRange = doc.body.createTextRange();
    preCaretTextRange.moveToElementText(element);
    preCaretTextRange.setEndPoint("EndToStart", textRange);
    start = preCaretTextRange.text.length;
    preCaretTextRange.setEndPoint("EndToEnd", textRange);
    end = preCaretTextRange.text.length;
  }
  return { start: start, end: end };
}
Copy after login

The above is the detailed content of How to Get the Start and End Offsets of a Text Selection Within a Container Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template