How to get carriage position in contenteditable div with html children elements in Internet Explorer

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

+4
source share
1 answer

Hi, I found an answer for Internet Explorer version 8 or lower.

  var cursorPosition=0; if (document.selection && document.selection.createRange) { range = document.selection.createRange(); if (range.parentElement() == YourEditableControl) { var tmpEle = document.createElement("span"); YourEditableControl.insertBefore(tmpEle, YourEditableControl.firstChild); var tmpRange = range.duplicate(); tmpRange.moveToElementText(tmpEle); tmpRange.setEndPoint("EndToEnd", range); cursorPosition= tmpRange.text.length; } } 

the above code solves my problem to find the current cursor position for IE8 or lower version since window.getSelection () is not changed for IE8 or lower and works fine with IE9

therefore, you can use the document.selection a selection object and the range object to get the current cursor shape or cursor position contenteditable div or other control

Hope this helps

+4
source

Source: https://habr.com/ru/post/1415305/


All Articles