Set text-cursor position in a textarea

前端 未结 6 1751
眼角桃花
眼角桃花 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:35

    Realizing this is an older question, this is offered only as something to think about as an option now because it may likely be more efficient than extracting and assembling pieces of the textarea value string, and it sets the cursor automatically based on the fourth argument of setRangeText and autofocuses also. It works in Firefox 66.0.02 and I haven't tested it elsewhere. The cursor is placed after the '[/b]'.

     t = document.getElementById("editor_area");
     b = t.selectionStart,
     e = t.selectionEnd + 3; // length of '[b]'
    
     t.setSelectionRange( b, b );
     t.setRangeText( '[b]' );
     t.setSelectionRange( e, e );
     t.setRangeText( '[/b]', e, e, 'end' );
    

提交回复
热议问题