【问题标题】:How to add a text to a textbox from the current position of the pointer with jquery?如何使用jquery从指针的当前位置向文本框添加文本?
【发布时间】:2013-04-05 06:55:35
【问题描述】:

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

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

【问题讨论】:

标签: jquery


【解决方案1】:

也许更短的版本,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) );
});

【讨论】:

【解决方案2】:

很巧,我只是在几分钟前回答了类似的question。您可以使用这样的自定义函数:

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

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

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

Working Demo

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多