cursor.js 2.14 KB
/**
 * 光标处理
 * @author: liqi <qi.li@yoho.cn>
 * @date: 2017/02/15
 */

var cursor = {
    posRecord: 0
};


/**
 * $.fn.extend 获取输入框光标位置
 * expample $(selector).recordCursor()
 */
$.fn.extend({
    recordCursor: function() {
        var pos = 0;
        var $sel;
        var $selLength;
        var $el = $(this).get(0);

        if ('selectionStart' in $el) {
            pos = $el.selectionStart;
        } else if ('selection' in document) {
            $el.focus();
            $sel = document.selection.createRange();
            $selLength = document.selection.createRange().text.length;

            $sel.moveStart('character', -$el.value.length);
            pos = $sel.text.length - $selLength;
        }
        cursor.posRecord = pos;
    }
});

$.extend(cursor, {
    /**
     * 设置光标位置
     * @param $el
     * @param pos
     */
    setCursor: function($el, pos) {
        var range;

        if ($el.setSelectionRange) {
            // chrome and firefox support
            $el.setSelectionRange(pos, pos);
            $el.focus();
        } else if ($el.createTextRange) {
            // IE support
            range = $el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    },

    /**
     * 在已记录光标处插入文本
     * @param text 文本
     */
    insertAtRecordCorsor: function(text) {
        var $el;
        var pos;
        var start;
        var end;
        var newVal;
        var self = cursor;
        var $area = $('.msg-area');
        var val = $area.val();
        var record = self.posRecord;

        if (record || record === 0) {
            start = val.substring(0, record);
            end = val.substring(record);
            newVal = [start, text, end].join('');
        } else {
            newVal = [val, text].join('');
        }

        $area.val(newVal);
        self.posRecord += text.length;

        $el = $area[0];
        pos = self.posRecord ? self.posRecord : newVal.length;
        this.setCursor($el, pos);
    }
});

module.exports = cursor;