5

我有一个带有一些单词和文本的文本框。我想做的是,当用户单击按钮时,从指针的当前位置向文本框的文本添加一些单词。如何做到这一点?这是文本框和按钮:

<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
4

2 回答 2

14

也许更短的版本,http://jsfiddle.net/NaHTw/4/会更容易理解?

jQuery("#btn").on('click', function() {
    var caretPos = document.getElementById("txt").selectionStart;
    var textAreaTxt = jQuery("#txt").val();
    var txtToAdd = "stuff";
    jQuery("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});
于 2013-04-12T17:08:16.000 回答
11

很巧,我几分钟前刚刚回答了一个类似的问题。您可以使用这样的自定义函数:

jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorer
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      //For browsers like Firefox and Webkit based
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  })
}
});

textbox基本上,这个插件允许你在多个或的插入符号处插入一段文本textarea。你可以像这样使用它:

 $('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');

Working Demo

于 2013-04-12T16:41:04.283 回答