Get cursor-position in contenteditable div

2019-02-20 11:39发布

问题:

I found the following code here on SO to get the position of the cursor of a contenteditable div, however it always returns 0.

The function that should retrieve the position:

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos;
    }
} (jQuery);

The code I use to test it:

$('div.MESSAGE_OF_DAY').keyup(function() {
  alert($(this).getCursorPosition()); // always returns 0???
});

I'm using Chrome (8.0.552.215) if it matters.

回答1:

The function you found is for finding the caret or selection in an input or textarea, not a contenteditable element. The caret/selection boundary position can be obtained in terms of a DOM node and offset within that node using the browser's Selection object to obtain a Range. I suggest reading about these objects (the links I've provided are a good starting point). In Internet Explorer, this process is completely different but you can use my Rangy library to eliminate the differences.