原文:https://blog.csdn.net/mafan121/article/details/78519348
html
<iframe id="editor" width="600px" height="400px" style="border:solid 1px;"></iframe> <input type="txt" onclick="alert(getPosition(event.target))"/>
js
//初始化编辑器 function init() { var ifr = document.getElementById("editor"); var doc = ifr.contentDocument || ifr.contentWindow.document; // W3C || IE doc.open(); doc.designMode="on"; doc.contentEditable = true; doc.write('<html><head><style>body{margin:3px; word-wrap:break-word; word-break: break-all; }</style></head><body>GoodNessEditor</body></html>'); doc.close(); console.log(doc.body.innerHTML); doc.addEventListener('click',function(e){ alert(getDivPosition(e)); }); } init(); //可编辑div获取坐标 var getDivPosition = function (event) { var element = event.target ? event.target : event; var caretOffset = 0; var doc = element.ownerDocument || element.document; var win = doc.defaultView || doc.parentWindow; var sel; if (typeof win.getSelection != "undefined") {//谷歌、火狐 sel = win.getSelection(); if (sel.rangeCount > 0) {//选中的区域 var range = win.getSelection().getRangeAt(0); var preCaretRange = range.cloneRange();//克隆一个选中区域 preCaretRange.selectNodeContents(element);//设置选中区域的节点内容为当前节点 preCaretRange.setEnd(range.endContainer, range.endOffset); //重置选中区域的结束位置 caretOffset = preCaretRange.toString().length; } } else if ((sel = doc.selection) && sel.type != "Control") {//IE var textRange = sel.createRange(); var preCaretTextRange = doc.body.createTextRange(); preCaretTextRange.moveToElementText(element); preCaretTextRange.setEndPoint("EndToEnd", textRange); caretOffset = preCaretTextRange.text.length; } return caretOffset; } //输入框获取光标 var getPosition = function (event) { var element = event.target ? event.target : event; let cursorPos = 0; if (document.selection) {//IE var selectRange = document.selection.createRange(); selectRange.moveStart('character', -element.value.length); cursorPos = selectRange.text.length; } else if (element.selectionStart || element.selectionStart == '0') { cursorPos = element.selectionStart; } return cursorPos; }