如何解决在光标使用 Javascript/jquery 的位置插入文本?

这里使用这个:

function insertAtCaret(areaId, text) {

  var txtarea = document.getElementById(areaId);

  if (!txtarea) {

    return;

  }



  var scrollPos = txtarea.scrollTop;

  var strPos = 0;

  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?

    "ff" : (document.selection ? "ie" : false));

  if (br == "ie") {

    txtarea.focus();

    var range = document.selection.createrange();

    range.moveStart('character', -txtarea.value.length);

    strPos = range.text.length;

  } else if (br == "ff") {

    strPos = txtarea.selectionStart;

  }



  var front = (txtarea.value).substring(0, strPos);

  var back = (txtarea.value).substring(strPos, txtarea.value.length);

  txtarea.value = front + text + back;

  strPos = strPos + text.length;

  if (br == "ie") {

    txtarea.focus();

    var ieRange = document.selection.createrange();

    ieRange.moveStart('character', -txtarea.value.length);

    ieRange.moveStart('character', strPos);

    ieRange.moveEnd('character', 0);

    ieRange.select();

  } else if (br == "ff") {

    txtarea.selectionStart = strPos;

    txtarea.selectionEnd = strPos;

    txtarea.focus();

  }



  txtarea.scrollTop = scrollPos;

}


<textarea id="textareaid"></textarea>

<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>

解决方法

我有一个包含很多文本框的页面。当有人单击链接时,我希望在光标所在的位置插入一两个词,或附加到具有焦点的文本框。

例如,如果光标/焦点位于显示“apple”的文本框上,并且他单击显示“[email]”的链接,那么我希望文本框显示“apple
bob@example.com”。

我怎样才能做到这一点?这甚至可能吗,因为如果焦点在单选/下拉/非文本框元素上怎么办?可以记住最后关注的文本框吗?