2013-05-09 13 views
0

當我單擊按鈕時,我想在當前插入符的位置插入一些文本到當前選定的文本區。我如何做到這一點與jQuery或只是Javascript?將文本插入選定的文本區

我來了一個跨文本插入到特定文本區域的代碼,但爲我的項目有多個文本區域。

+0

:)多個textareas,好的,但是你只能有一個脫字號的位置,而不是多個。 – 2013-05-09 05:24:03

+1

爲什麼我的問題被拒絕投票? – 2013-05-11 04:01:28

回答

1

這確實全部你想要什麼(除了舊的瀏覽器支持)。

var myText = "sup?", 
    lastActiveElement = null; 

window.addEventListener("focusin", function(e) { 
    lastActiveElement = e.target; 
}); 

document.getElementById("go").addEventListener("click", function(e) { 
    if(!lastActiveElement || lastActiveElement.tagName.toUpperCase() !== "TEXTAREA") { 
     alert("no textarea selected"); 
     return; 
    } 
    var selectionStart = lastActiveElement.selectionStart, 
     value = lastActiveElement.value; 
    lastActiveElement.value = value.substr(0, selectionStart) + myText + value.substr(selectionStart); 
}); 

演示:http://jsfiddle.net/rfYZq/2/

focusin事件存儲最後聚焦元素成變種。

0
(function ($, undefined) { 
    $.fn.getCursorPosition = function() { 
     var el = $(this).get(0); 
     var pos = 0; 
     if('selectionStart' in el) { 
      pos = el.selectionStart; 
     } else if('selection' in document) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength; 
     } 
     return pos; 
    } 
})(jQuery); 

基本上,使用它上的文本框,請執行下列操作:

$("#myTextBoxSelector").getCursorPosition(); 
0

我從別的地方拿到這個劇本,但我找不到書籤它。

這增加了jQuery的一個方法,可以讓你做到以下幾點:

$("#selectedTextarea").insertAtCaret(myText); 

編輯:工作小提琴here

,代碼:

jQuery.fn.extend({ 
insertAtCaret: function(myValue) 
{ 
    return this.each(function() 
    { 
     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(); 
     } 
    }) 
} 
}); 
+0

這非常接近,但我只有一個按鈕和多個textareas。我編輯了你的小提琴展示。你如何找到目前選擇哪個textarea? http://jsfiddle.net/MxBve/1/ – 2013-05-09 15:16:59