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

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

    Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:

    function caretPosition(input) {
        var start = input[0].selectionStart,
            end = input[0].selectionEnd,
            diff = end - start;
    
        if (start >= 0 && start == end) {
            // do cursor position actions, example:
            console.log('Cursor Position: ' + start);
        } else if (start >= 0) {
            // do ranged select actions, example:
            console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
        }
    }
    

    Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery .on()). For performance reasons, it may be a good idea to add setTimeout() or something like Underscores _debounce() if events are pouring in:

    $('input[type="text"]').on('keyup mouseup mouseleave', function() {
        caretPosition($(this));
    });
    

    Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/

提交回复
热议问题