jquery - js input focus position




textarea中的光標位置(字符索引,而不是x/y坐標) (4)

如何使用jQuery在textarea中獲得插入符號的位置? 我正在尋找光標從文本開頭的偏移,而不是(x,y)位置


不是jQuery,而只是Javascript ......

var position = window.getSelection().getRangeAt(0).startOffset;

修改了BojanG的解決方案以使用jQuery。 在Chrome,FF和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);

基本上,要在文本框中使用它,請執行以下操作:

$("#myTextBoxSelector").getCursorPosition();

這也適用於IE9,Firefox和Chrome:

(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);

而且我覺得它比Ryan的版本要乾淨得多



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;

}




cursor-position