Calculating Range Start and End Offsets Relative to Parent Container
Suppose you encounter HTML elements like the one below:
<div>
And a user selects the text "home" with their mouse. Determining the character offsets within the "#parent" element is a common task, especially when selecting HTML tags.
While the "range.startOffset" property provides an offset relative to the immediate container, it's limited to character offsets when the container is a text node. To overcome this limitation, we present an updated solution:
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 }; }
To demonstrate the updated method, we initialize event listeners to capture selection changes and update a log element on the page:
function reportSelection() { var selOffsets = getSelectionCharacterOffsetWithin( document.getElementById("editor") ); document.getElementById("selectionLog").innerHTML = "Selection offsets: " + selOffsets.start + ", " + selOffsets.end; } window.onload = function () { document.addEventListener("selectionchange", reportSelection, false); document.addEventListener("mouseup", reportSelection, false); document.addEventListener("mousedown", reportSelection, false); document.addEventListener("keyup", reportSelection, false); };
This code enables you to accurately determine the character offsets of a user's selection within an HTML element, even when selecting HTML tags.
The above is the detailed content of How to Accurately Determine Character Offsets Within an HTML Element?. For more information, please follow other related articles on the PHP Chinese website!