Set text-cursor position in a textarea

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

    This is a little OT, but if anyone is interested:

    • Brief: Set cursor inside input element throug row and column
    • Dependency: setSelectionRange() from @ashkan nasirzadeh
    • Example call: setTextCursor(textarea,textarea.val, 0, 1);

      // @brief: set cursor inside _input_ at position (column,row)
      // @input: input DOM element. E.g. a textarea
      // @content: textual content inside the DOM element
      // @param row: starts a 0
      // @param column: starts at 0    
      function setTextCursor(input, content, row, column){
        // search row times: 
        var pos = 0;
        var prevPos = 0;
        for( var i = 0; (i lineEndPos-pos)){
            // go *only* to the end of the current line
            pos = lineEndPos;
        } else{
            // act as usual
            pos += column
        }
      
        setSelectionRange(input, pos,pos);
      }
      

提交回复
热议问题