如何在textarea中的当前插入位置插入文本

在来自图像的函数调用中,我试图将图像中的alt标记值插入到插入符当前所在位置的textarea中。

这是我目前拥有的代码,它将alt标记值插入文本区域的末尾。

$("#emoticons").children().children().click(function () { var ch = $(this).attr("alt"); $("#txtPost").append(ch); }); 

我遇到问题的两件事是确定插入符号的位置,并在插入符号位置+插入的代码+插入符号后的textarea的值之前创建一个带有textarea值的新字符串。

我现在有这个扩展到位:

 $.fn.insertAtCaret = function(text) { return this.each(function() { if (document.selection && this.tagName == 'TEXTAREA') { //IE textarea support this.focus(); sel = document.selection.createRange(); sel.text = text; this.focus(); } else if (this.selectionStart || this.selectionStart == '0') { //MOZILLA/NETSCAPE support startPos = this.selectionStart; endPos = this.selectionEnd; scrollTop = this.scrollTop; this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length); this.focus(); this.selectionStart = startPos + text.length; this.selectionEnd = startPos + text.length; this.scrollTop = scrollTop; } else { // IE input[type=text] and other browsers this.value += text; this.focus(); this.value = this.value; // forces cursor to end } }); }; 

你可以像这样使用它:

 $("#txtPost").insertAtCaret(ch);