`
fackyou200
  • 浏览: 300719 次
  • 性别: Icon_minigender_1
  • 来自: 山西太原
社区版块
存档分类
最新评论

textarea光标处插入内容,兼容IE、方法、chrome,可模拟表情

    博客分类:
  • js
 
阅读更多
/**
 * 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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics