cursor.js
2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* 光标处理
* @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;