Home > Web Front-end > JS Tutorial > How Can I Precisely Control Caret Position in a Contenteditable Div?

How Can I Precisely Control Caret Position in a Contenteditable Div?

Susan Sarandon
Release: 2024-12-11 05:05:13
Original
350 people have browsed it

How Can I Precisely Control Caret Position in a Contenteditable Div?

Caret Positioning in Contenteditable Elements

Seeking to manipulate the caret position within a contenteditable div, many attempts have been made to harness the Range and Selection objects with varying degrees of success. However, recent endeavors have uncovered precise methods for setting the cursor's placement:

Setting the Caret to a Specific Character

In browsers like Firefox and Chrome, the desired result can be achieved by utilizing the following code:

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)
}
Copy after login

In this code, the cursor is positioned at the fifth character of the second line of text in the contenteditable div with the id "editable." This is accomplished by specifying the target node (el.childNodes[2]) and the offset position (5) within that node for both the start and end points of the range.

Refining the Position

For maximum precision, additional nodes and offsets can be included in the code to narrow the cursor's placement to a specific character within a nested element or even within a specific word. This level of control allows for seamless cursor manipulation within complex HTML structures.

The above is the detailed content of How Can I Precisely Control Caret Position in a Contenteditable Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template