2013-04-12 20 views
4

我發現JQuery InsertAtCaret函數Here但是沒有詳細說明如何使用它。我已經嘗試了很多,以瞭解它如何使用,但找不到任何方法。這是功能。如何使用JQuery InsertAtCaret函數

$.fn.insertAtCaret = function(myValue) { 
    return this.each(function() { 
     var me = this; 
     if (document.selection) { // IE 
      me.focus(); 
      sel = document.selection.createRange(); 
      sel.text = myValue; 
      me.focus(); 
     } else if (me.selectionStart || me.selectionStart == '0') { // Real browsers 
      var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop; 
      me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length); 
      me.focus(); 
      me.selectionStart = startPos + myValue.length; 
      me.selectionEnd = startPos + myValue.length; 
      me.scrollTop = scrollTop; 
     } else { 
      me.value += myValue; 
      me.focus(); 
     } 
    }); 
}; 

我有一個文本框輸入字段和它下面的textarea。我應該在哪裏調用這個函數,我應該給它什麼值。在哪裏我必須給我的textarea的參考。

+1

你可能想嘗試留在[在GitHub上的要點](評論https://gist.github.com/mathiasbynens/ 326491)。通常情況下,腳本的作者將非常樂意解釋它的使用,有時很高興知道他們的代碼正在幫助peiple。 –

+2

查看代碼,只需在當前插入符處添加'myValue'中包含的文本。我猜''('#myTextarea')。insertAtCaret('我的新文本')'應該可以工作 – Uby

回答

6

在這裏被修改上述插件的版本:

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

+0

謝謝。這真的很不錯。 –

相關問題