/** * tId 文本域Id * tag 插入内容 */ ffunction addEmoticon(tId,tag) { var txtarea = document.getElementById(tId); //IE if(document.selection) { var theSelection = document.selection.createRange().text; if(!theSelection) { theSelection=tag} txtarea.focus(); if(theSelection.charAt(theSelection.length - 1) == " "){ theSelection = theSelection.substring(0, theSelection.length - 1); document.selection.createRange().text = theSelection+ " "; } else { document.selection.createRange().text = theSelection; } } // Mozilla else if(txtarea.selectionStart || txtarea.selectionStart == '0'){ var startPos = txtarea.selectionStart; var endPos = txtarea.selectionEnd; var myText = (txtarea.value).substring(startPos, endPos); if(!myText) { myText=tag;} if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any subst = myText.substring(0, (myText.length - 1))+ " "; } else { subst = myText; } txtarea.value = txtarea.value.substring(0, startPos) + subst + txtarea.value.substring(endPos, txtarea.value.length); txtarea.focus(); var cPos=startPos+(myText.length); txtarea.selectionStart=cPos; txtarea.selectionEnd=cPos; } // All others else{ txtarea.value+=tag; txtarea.focus(); } if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate(); }
jquery写法(主要部分):
(function($) {
$.fn.insertAtCaret = function (tagName) {
return this.each(function(){
if (document.selection) {
//IE support
var theSelection = document.selection.createRange().text;
if(!theSelection) { theSelection=tagName}
this.focus();
if(theSelection.charAt(theSelection.length - 1) == " "){
theSelection = theSelection.substring(0, theSelection.length - 1);
document.selection.createRange().text = theSelection+ " ";
} else {
document.selection.createRange().text = theSelection;
}
}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) + tagName + this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + tagName.length;
this.selectionEnd = startPos + tagName.length;
this.scrollTop = scrollTop;
} else {
this.value += tagName;
this.focus();
}
if(this.createTextRange) this.caretPos = document.selection.createRange().duplicate();
});
};
})(jQuery);
转:http://www.zhudongdong.cn/html/347.html