textarea光标处插入内容,兼容IE、方法、chrome,可模拟表情
/**
* 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
相关推荐
86417413 2020-11-25
simonzhao0 2020-11-23
HappyBlog 2020-10-27
del 2020-10-21
ChromeDisaster 2020-10-11
svap 2020-08-25
simonzhao0 2020-08-17
shayuchaor 2020-08-17
yidaizongshi 2020-08-16
化风 2020-08-14
tiankele0 2020-07-29
maowenbei 2020-07-19
curiousL 2020-07-18
王练 2020-07-18
liuweiq 2020-07-08