jQuery - 在textarea中插入文本后定位光标

时间:2016-01-29 01:49:52

标签: jquery position cursor textarea

我的问题很简单,但我无法理解。

我正在使用here周围找到的方法在textarea中插入文本。那个方法,将文本插入实际的光标位置,没关系。

但我想将光标定位在插入的文本之间。 我要插入的文字是:****__~~~~[](http://) 我知道,这只是一些随机符号。但这是一个eregi。 我想将光标放在插入的字符之间,**here**_here_~~HERE~~之间,我需要在第一个[]之间定位的最后一个,它是[HERE](http://)

它不应该那么难,但我只是不知道该怎么做。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

使用以下功能:

工作示例Caret Test

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

$("#addStarsCode").click(function() {
  var my_i_val = $("#my_textarea").val();

  $("#my_textarea").val(my_i_val + '****');
  setCaretToPos($("#my_textarea")[0], $("#my_textarea").val().length-2);
});
<textarea id=my_textarea name=my_textarea> I Am A Default Text</textarea><br>
<button id=addStarsCode>Add ****</button>
相关问题