简体   繁体   中英

Contenteditable Div - Cursor position in terms of innerHTML position

I've done my research and come across these questions on StackOverflow where people asked this same question but the thing is that they wanted to get the position either in terms of x and y coordinates or column from the left. I want to know what the position of the cursor is with respect to the div's innerHTML.

For example:

innerHTML = "This is the innerHTML of the <b>div</b> and bla bla bla..."
                                                        ^
                                                  Cursor is here

So the result I want for this case is 44. How to do it ?

var target = document.createTextNode("\u0001");
document.getSelection().getRangeAt(0).insertNode(target);
var position = contentEditableDiv.innerHTML.indexOf("\u0001");
target.parentNode.removeChild(target);

This temporarily inserts a dummy text node containing a non-printable character ( \ ), and then finds the index of that character within the div 's innerHTML .

For the most part this leaves the DOM and the current selection unchanged, with one minor possible side effect: if the cursor is in the middle of text from a single text node, that node will be broken up into two consecutive text nodes. Usually that should be harmless, but keep it in mind in the context of your specific application.

UPDATE: Turns out you can merge the consecutive text nodes using Node.normalize() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM