本文实例讲述了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') {
var startpos = $t.selectionstart;
var endpos = $t.selectionend;
var scrolltop = $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程序设计有所帮助。