Set keyboard caret position in html textbox

后端 未结 9 2684
时光说笑
时光说笑 2020-11-22 00:02

Does anybody know how to move the keyboard caret in a textbox to a particular position?

For example, if a text-box (e.g. input element, not text-area) has 50 charact

9条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 00:15

    The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

    http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

    In case the code gets lost again, here are the two main functions:

    function doGetCaretPosition(ctrl)
    {
     var CaretPos = 0;
    
     if (ctrl.selectionStart || ctrl.selectionStart == 0)
     {// Standard.
      CaretPos = ctrl.selectionStart;
     }
     else if (document.selection)
     {// Legacy IE
      ctrl.focus ();
      var Sel = document.selection.createRange ();
      Sel.moveStart ('character', -ctrl.value.length);
      CaretPos = Sel.text.length;
     }
    
     return (CaretPos);
    }
    
    
    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();
     }
    }
    

提交回复
热议问题