Home >Web Front-end >JS Tutorial >How Can I Get the Caret Position in a ContentEditable Element?
Retrieving the Caret Position in a ContentEditable Element
In contrast to the abundance of solutions for setting the caret position within contentEditable elements, determining its current position has proven elusive for many developers. This question addresses this specific knowledge gap.
To ascertain the caret position within a given contentEditable element upon user input, such as keypresses, one can utilize the following code:
function getCaretPosition(editableDiv) { var caretPos = 0, sel, range; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0); if (range.commonAncestorContainer.parentNode == editableDiv) { caretPos = range.endOffset; } } } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); if (range.parentElement() == editableDiv) { var tempEl = document.createElement("span"); editableDiv.insertBefore(tempEl, editableDiv.firstChild); var tempRange = range.duplicate(); tempRange.moveToElementText(tempEl); tempRange.setEndPoint("EndToEnd", range); caretPos = tempRange.text.length; } } return caretPos; }
This code operates under the following assumptions:
For a more comprehensive solution that accommodates more complex content with nested elements, refer to the following Stack Overflow answer: https://stackoverflow.com/a/4812022/96100
The above is the detailed content of How Can I Get the Caret Position in a ContentEditable Element?. For more information, please follow other related articles on the PHP Chinese website!