[英]How to insert text at the current caret position in a 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.