I am working with a contenteditable div that will have the ability to have inline html elements, such as the "<p> <font> <br>" tags in a text stream.
At certain points, I need to grab the carriage position (cursor position) contenteditable div, cursor (cursor) after the html child.
I use the following code in javascript for Firefox, it works correctly to find the carriage position (cursor position) of the contenteditable div, but I did not find any solution for Internet Explorer to find the carriage position (cursor position), because window.getSelection
undefined.
function getCaretPosition() { if (window.getSelection && window.getSelection().getRangeAt) { var range = window.getSelection().getRangeAt(0); var selectedObj = window.getSelection(); var rangeCount = 0; var childNodes = selectedObj.anchorNode.parentNode.childNodes; for (var i = 0; i < childNodes.length; i++) { if (childNodes[i] == selectedObj.anchorNode) { break; } if (childNodes[i].outerHTML) rangeCount += childNodes[i].outerHTML.length; else if (childNodes[i].nodeType == 3) { rangeCount += childNodes[i].textContent.length; } } return range.startOffset + rangeCount; } return -1; }
I found that document.selection;
works in Internet Expolrer, but I donβt think it will work for me to find the caret position (cursor position) of a contenteditable div.
Does anyone have any work for me.
in the example below, my cursor position is between "t" and "w" in <p> 2 </p> <div contenteditable="true"><p>one<br><b>t|wo</b></p></div>
I assume that you need the number 14 in the example above, since I need to perform some operation at this point. I use this contenteditable div since a RichTextbox with my custom style is applicable to it
source share