I can get the cursor position now, but this is the correct position without line wrapping. If there is a line break, the location obtained is incorrect! Always get the location of the first line, not the actual location of the cursor.
how to get the position of the cursor correctly (in the case of multiple lines of text, get the location of the cursor correctly)?
here is the code for me to get the location of the cursor:
// :
SmallJs.getSelectionForInput = function(dom){
return {
startOffset: dom.selectionStart ,
endOffset: dom.selectionEnd
};
};
// html:
SmallJs.getSelectionForContentEditableElement = function(dom){
var selection = window.getSelection();
if (selection.rangeCount === 0) {
return false;
}
var range = selection.getRangeAt(0);
console.log(range);
var cRange = range.cloneRange();
cRange.selectNodeContents(dom);
cRange.setStart(range.startContainer , range.startOffset);
cRange.setEnd(range.endContainer , range.endOffset);
return {
startOffset: range.startOffset ,
endOffset: range.endOffset
};
};
//
SmallJs.getSelection = function(dom){
if (dom.contentEditable !== "true") {
return this.getSelectionForInput(dom);
}
return this.getSelectionForContentEditableElement(dom);
};