js实现文本框文本域光标处插入图片文本的插件(并且光标在插入内容的内容后显示)

时间:2023-03-09 18:14:00
js实现文本框文本域光标处插入图片文本的插件(并且光标在插入内容的内容后显示)

js:

/*******************************************
 *
 * 插入光标处的插件
 * @authors Du xin li
 * @update    2015-10-25
 *
*********************************************/

$.fn.extend({  
    insertContent : function(myValue, t) {  
        var that = $(this);
        var $t = $(this)[0];  
        if (document.selection) {  
            this.focus();  
            var sel = document.selection.createRange();  
            sel.text = myValue;  
            this.focus();  
            sel.moveStart('character', -l);  
            var wee = sel.text.length;  
            if (arguments.length == 2) {  
            var l = $t.value.length;  
            sel.moveEnd("character", wee + t);  
            t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);  
            sel.select();  
            }  
        } 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;  
            if (arguments.length == 2) {
                $t.setSelectionRange(startPos - t,$t.selectionEnd + t);  
                this.focus();
            }  
        } else {                              
            this.value += myValue;                              
            this.focus();  
        }  
    }  
})

使用方法:

/**
* 点击表情按钮插入表情方法
* @param {string} dom 任意子节点
* @param {Object} event event对象
*/
fc.emote = function(dom, event){
if (dom) {
this.setParam(dom);
} else {
return false;
}
var that = $(dom);
var e = window.event || event;
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble = true;
}
//显示表情弹出层
$('.fresh-dialog-emote').removeClass('hide');
//当前文本框textarea
var _currentTextarea = this.param.form;
//点击表情插入文本框
$('.fresh-dialog-emote').off('click', '.fresh-jsSmilies li').on('click', '.fresh-jsSmilies li', function(){
var _val = $(this).data('action');
console.log(_val)
console.log(_currentTextarea.length)
_currentTextarea.focus();
_currentTextarea.insertContent(_val);
$('.fresh-dialog-emote').addClass('hide');
})
}

// 点击表情按钮,弹出表情弹出层
$('.fresh-list').off('click', '.fresh-comment-emote-btn').on('click', '.fresh-comment-emote-btn', function(event){
fresh.comment.emote(this, event);
});