1. 程式人生 > >獲取游標位置

獲取游標位置

原文: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; }