Javascript 在 textarea 中设置文本光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34968174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:07:21  来源:igfitidea点击:

Set text-cursor position in a textarea

javascripttextarea

提问by BuSaeed

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

我正在开发 BBCode 编辑器,代码如下:

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

            function boldText() {
                var start = txtarea.selectionStart;
                var end = txtarea.selectionEnd;
                var sel = txtarea.value.substring(start, end);
                var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
                txtarea.value = finText;
                txtarea.focus();
            }

Everything is OK except one thing which is the position of the text-cursor. When I click on the boldText button, it sets the cursor position at the end of the Textarea!!

除了文本光标的位置之外,一切都很好。当我单击boldText 按钮时,它会将光标位置设置在Textarea 的末尾!!

Actually, I want to be able to set the cursor position at a certain index. I want something like this:

实际上,我希望能够将光标位置设置在某个索引处。我想要这样的东西:

txtarea.setFocusAt(20);

回答by Rick Hitchcock

After refocusing the textarea with txtarea.focus(), add this line:

使用 重新聚焦 textarea 后txtarea.focus(),添加以下行:

txtarea.selectionEnd= end + 7;

That will set the cursor seven positions ahead of where it was previously, which will take [b][/b]into account.

这会将光标设置在它之前的位置前七个位置,这将考虑[b][/b]在内。

Example

例子

document.getElementById('bold').addEventListener('click', boldText);

function boldText() {
  var txtarea = document.getElementById("editor_area");
  var start = txtarea.selectionStart;
  var end = txtarea.selectionEnd;
  var sel = txtarea.value.substring(start, end);
  var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
  txtarea.value = finText;
  txtarea.focus();
  txtarea.selectionEnd= end + 7;
}
#editor_area {
  width: 100%;
  height: 10em;
}
<button id="bold">B</button>
<textarea id="editor_area"></textarea>

回答by Mubashar Abbas

if you are using jquery you can do it like this.

如果你使用 jquery,你可以这样做。

$('textarea').prop('selectionEnd', 13);

回答by ashkan nasirzadeh

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

您可以使用下面由Jamie Munro( setSelectionRange()& setCaretToPos())编写的这 2 个函数:

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);

例如,如果您想在 textarea 的末尾设置插入符号,您可以使用以下命令: setCaretToPos(document.getElementById('textarea'), -1);

回答by DarkTrick

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<row) && (pos != -1); ++i){
          prevPos = pos;
          pos = content.indexOf("\n",pos+1);        
      }
    
    
      // if we can't go as much down as we want,
      //  go as far as worked
      if(-1 == pos){ pos = prevPos; }
    
      if(0 != row)
          ++pos; // one for the linebreak
    
      // prevent cursor from going beyond the current line
      var lineEndPos = content.indexOf("\n", pos+1);
    
      if((-1 != lineEndPos) && 
          (column > lineEndPos-pos)){
          // go *only* to the end of the current line
          pos = lineEndPos;
      } else{
          // act as usual
          pos += column
      }
    
      setSelectionRange(input, pos,pos);
    }
    
  • 简介:通过行和列在输入元素内设置光标
  • 依赖setSelectionRange()来自@ashkan nasirzadeh
  • 示例调用: 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<row) && (pos != -1); ++i){
          prevPos = pos;
          pos = content.indexOf("\n",pos+1);        
      }
    
    
      // if we can't go as much down as we want,
      //  go as far as worked
      if(-1 == pos){ pos = prevPos; }
    
      if(0 != row)
          ++pos; // one for the linebreak
    
      // prevent cursor from going beyond the current line
      var lineEndPos = content.indexOf("\n", pos+1);
    
      if((-1 != lineEndPos) && 
          (column > lineEndPos-pos)){
          // go *only* to the end of the current line
          pos = lineEndPos;
      } else{
          // act as usual
          pos += column
      }
    
      setSelectionRange(input, pos,pos);
    }
    

回答by Ranjeet

Through JQuery:

通过 JQuery:

    var cursorPos = $('#textarea').prop('selectionStart');
    $('#textarea').prop('selectionEnd',cursorPos-2);

回答by Gary

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 setRangeTextand autofocuses also. It works in Firefox 66.0.02 and I haven't tested it elsewhere. The cursor is placed after the '[/b]'.

意识到这是一个较旧的问题,这仅作为现在考虑的选项提供,因为它可能比提取和组装 textarea 值字符串的片段更有效,并且它会根据第四个参数自动设置光标setRangeText和自动对焦也。它适用于 Firefox 66.0.02,我没有在其他地方测试过。光标放在'[/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' );