Set keyboard caret position in html textbox

后端 未结 9 2545
时光说笑
时光说笑 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:07

    I would fix the conditions like below:

    function setCaretPosition(elemId, caretPos)
    {
     var elem = document.getElementById(elemId);
     if (elem)
     {
      if (typeof elem.createTextRange != 'undefined')
      {
       var range = elem.createTextRange();
       range.move('character', caretPos);
       range.select();
      }
      else
      {
       if (typeof elem.selectionStart != 'undefined')
        elem.selectionStart = caretPos;
       elem.focus();
      }
     }
    }
    

提交回复
热议问题