Javascript獲取以及設(shè)置光標(biāo)位置

字號(hào):


    在項(xiàng)目開發(fā)中經(jīng)常遇到input等設(shè)置光標(biāo)位置到最后的問題,今天我查了一下Google,找到了在IE、Firefox、Opera等主流瀏覽器的獲取光標(biāo)位置(getCursortPosition)以及設(shè)置光標(biāo)位置(setCursorPosition)的函數(shù)。
    獲取光標(biāo)位置函數(shù)
    [js]代碼:
    function getCursortPosition (ctrl) {
    var CaretPos = 0;// IE Support
    if (document.selection) {
    ctrl.focus ();
    var Sel = document.selection.createRange ();
    Sel.moveStart ('character', -ctrl.value.length);
    CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
    CaretPos = ctrl.selectionStart;
    return (CaretPos);
    }
    設(shè)置光標(biāo)位置函數(shù)
    [js]代碼:
    function setCaretPosition(ctrl, pos){
    if(ctrl.setSelectionRange)
    {
    ctrl.focus();
    ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
    var range = ctrl.createTextRange();
    range.collapse(true);
    range.moveEnd('character', pos);
    range.moveStart('character', pos);
    range.select();
    }
    }