Get cursor position (in characters) within a text Input field

后端 未结 9 1392
孤城傲影
孤城傲影 2020-11-22 01:22

How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something lik

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 01:32

    Nice one, big thanks to Max.

    I've wrapped the functionality in his answer into jQuery if anyone wants to use it.

    (function($) {
        $.fn.getCursorPosition = function() {
            var input = this.get(0);
            if (!input) return; // No (input) element found
            if ('selectionStart' in input) {
                // Standard-compliant browsers
                return input.selectionStart;
            } else if (document.selection) {
                // IE
                input.focus();
                var sel = document.selection.createRange();
                var selLen = document.selection.createRange().text.length;
                sel.moveStart('character', -input.value.length);
                return sel.text.length - selLen;
            }
        }
    })(jQuery);
    

提交回复
热议问题