Given an HTML element, how can one determine the character offsets within the parent container where a range (user selection) starts and ends, even when the selection spans HTML tags?
Updated Response:
To obtain both start and end offsets:
function getSelectionCharacterOffsetWithin(element) { // Determine start and end offsets var start = 0; var end = 0; // Create ranges var range = getRangeAt(0); var preCaretRange = range.cloneRange(); // Set start offset preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.startContainer, range.startOffset); start = preCaretRange.toString().length; // Set end offset preCaretRange.setEnd(range.endContainer, range.endOffset); end = preCaretRange.toString().length; // Return the object return { start: start, end: end }; }
Original Response:
The provided code utilizes getSelection() and getRangeAt(0) to retrieve the selection. It then calculates the offset of the caret position within the element using the toString() method on the range. This approach only provides the end offset or caret position.
Example:
function getRangeCharacterOffsetWithin(element) { var range, sel; if ((sel = window.getSelection())) { range = sel.getRangeAt(0); range.collapse(false); prevRange = range.cloneRange(); prevRange.selectNodeContents(element); prevRange.setEnd(range.endContainer, range.endOffset); return prevRange.toString().length; } return 0; }
The above is the detailed content of How Can I Determine the Start and End Character Offsets of a User Selection Within Its Parent HTML Element?. For more information, please follow other related articles on the PHP Chinese website!