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

后端 未结 9 1233
孤城傲影
孤城傲影 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:41

    There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.

    var input = document.getElementById('myinput'); // or $('#myinput')[0]
    var caretPos = input.selectionStart;
    
    // and if you want to know if there is a selection or not inside your input:
    
    if (input.selectionStart != input.selectionEnd)
    {
        var selectionValue =
        input.value.substring(input.selectionStart, input.selectionEnd);
    }
    
    0 讨论(0)
  • 2020-11-22 01:48
       (function($) {
        $.fn.getCursorPosition = function() {
            var input = this.get(0);
            if (!input) return; // No (input) element found
            if (document.selection) {
                // IE
               input.focus();
            }
            return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
         }
       })(jQuery);
    
    0 讨论(0)
  • 2020-11-22 01:50

    There is now a nice plugin for this: The Caret Plugin

    Then you can get the position using $("#myTextBox").caret() or set it via $("#myTextBox").caret(position)

    0 讨论(0)
提交回复
热议问题