Set text-cursor position in a textarea

前端 未结 6 2195
眼角桃花
眼角桃花 2021-01-01 13:18

I\'m working on a BBCode editor and here is the code:

var txtarea = document.getElementById(\"editor_area\");

            function boldText() {
                     


        
6条回答
  •  半阙折子戏
    2021-01-01 13:53

    you can use these 2 functions below written by Jamie Munro (setSelectionRange() & setCaretToPos()):

    function setSelectionRange(input, selectionStart, selectionEnd) {
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }
        else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        }
    }
    
    function setCaretToPos (input, pos) {
           setSelectionRange(input, pos, pos);
    }
    

    EXAMPLE:

    for example, if you want to set the caret at the end of your textarea you can have this: setCaretToPos(document.getElementById('textarea'), -1);

提交回复
热议问题