jQuery实现在textarea指定位置插入字符或表情的方法
本文实例讲述了jQuery实现在textarea指定位置插入字符或表情的方法。分享给大家供大家参考。具体实现方法如下:
1.函数定义
(function($){
$.fn.extend({
insertAtCaret:function(myValue){
var$t=$(this)[0];
if(document.selection){
this.focus();
sel=document.selection.createRange();
sel.text=myValue;
this.focus();
}
else
if($t.selectionStart||$t.selectionStart=='0'){
varstartPos=$t.selectionStart;
varendPos=$t.selectionEnd;
varscrollTop=$t.scrollTop;
$t.value=$t.value.substring(0,startPos)+myValue+$t.value.substring(endPos,$t.value.length);
this.focus();
$t.selectionStart=startPos+myValue.length;
$t.selectionEnd=startPos+myValue.length;
$t.scrollTop=scrollTop;
}
else{
this.value+=myValue;
this.focus();
}
}
})
})(jQuery);2.调用方法
$("#textareaId").insertAtCaret("新表情");
希望本文所述对大家的jQuery程序设计有所帮助。