📜  在 contenteditable div 中获取光标位置 - 无论代码示例

📅  最后修改于: 2022-03-11 14:59:58.405000             🧑  作者: Mango

代码示例1
function cursor_position() {
    var sel = document.getSelection();
    
    var pos = sel.toString().length;
    if(sel.anchorNode != undefined) sel.collapseToEnd();

    return pos;
}

// Demo:
var elm = document.querySelector('[contenteditable]');
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)

function printCaretPosition(){
  console.log( cursor_position(), 'length:', this.textContent.trim().length )
}