Позиция курсора в текстовой области (индекс символа, не x/y координаты)

Как я могу получить положение каре в текстовой области с помощью jQuery? Я ищу смещение курсора от запуска текста, не для (x, y) положение.

57
задан Dan Dascalescu 14 March 2014 в 09:34
поделиться

3 ответа

Не jQuery, а просто Javascript ...

var position = window.getSelection().getRangeAt(0).startOffset;
8
ответ дан 24 November 2019 в 19:26
поделиться

function caretPos(el)
{
    var pos = 0;
    // IE Support
    if (document.selection) 
    {
        el.focus ();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart ('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    // Firefox support
    else if (el.selectionStart || el.selectionStart == '0')
        pos = el.selectionStart;

    return pos;

}
13
ответ дан 24 November 2019 в 19:26
поделиться

Modified BojanG's solution to work with jQuery. Tested in Chrome, FF, and IE.

(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

Basically, to use it on a text box, do the following:

$("#myTextBoxSelector").getCursorPosition();
86
ответ дан 24 November 2019 в 19:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: