jQuery Set Cursor Position in Text Area

前端 未结 16 1483
无人共我
无人共我 2020-11-21 11:42

How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when

16条回答
  •  盖世英雄少女心
    2020-11-21 12:05

    This works for me in chrome

    $('#input').focus(function() {
        setTimeout( function() {
            document.getElementById('input').selectionStart = 4;
            document.getElementById('input').selectionEnd = 4;
        }, 1);
    });
    

    Apparently you need a delay of a microsecond or more, because usually a user focusses on the text field by clicking at some position in the text field (or by hitting tab) which you want to override, so you have to wait till the position is set by the user click and then change it.

提交回复
热议问题