在textarea指定位置插入字符或表情
來源:程序員人生 發布時間:2014-02-27 01:48:39 閱讀次數:2661次
jQuery 實現在textarea指定位置插入字符或表情,這個實例需要您在網頁中引入jQuery框架,同時以下代碼也要引入:
(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);
調用方法:
$("#textareaId").insertAtCaret("新表情");