Get the Starting and Ending Positions of a Text Selection Relative to Its Container
Problem:
Consider the following HTML:
<div>
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 }; }
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!