Setting the caret position in a contenteditable div can be achieved using the Range and Selection objects. Here's how to set the caret to a specific position within the element:
function setCaret() { var el = document.getElementById("editable") var range = document.createRange() var sel = window.getSelection() range.setStart(el.childNodes[2], 5) range.collapse(true) sel.removeAllRanges() sel.addRange(range) }
Consider the following HTML:
<div>
When you click the "focus" button, the JavaScript function setCaret() is invoked, placing the caret at the fifth character of the second line of text.
The above is the detailed content of How to Programmatically Set the Caret Position in a ContentEditable Element?. For more information, please follow other related articles on the PHP Chinese website!