Set keyboard caret position in html textbox

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

    I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.

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

提交回复
热议问题