broswer.js
2.93 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/**
* 浏览器相关功能扩展
* @author: liqi <qi.li@yoho.cn>
* @date: 2016/11/26
*/
var $ = require('yoho-jquery');
var state;
var isHidden;
var changeEvent;
/**
* 获取光标位置
*/
function _getCursorPosition() {
var sel,
pos = 0,
selLength,
el = $(this).get(0);
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
sel = document.selection.createRange();
selLength = document.selection.createRange().text.length;
el.focus();
sel.moveStart('character', -el.value.length);
pos = sel.text.length - selLength;
}
return pos;
}
/**
* 判断当前tab页是否可见
*/
function tabIsHidden() {
if (typeof document.hidden !== 'undefined') {
changeEvent = 'visibilitychange';
state = 'visibilityState';
} else if (typeof document.mozHidden !== 'undefined') {
changeEvent = 'mozvisibilitychange';
state = 'mozVisibilityState';
} else if (typeof document.msHidden !== 'undefined') {
changeEvent = 'msvisibilitychange';
state = 'msVisibilityState';
} else if (typeof document.webkitHidden !== 'undefined') {
changeEvent = 'webkitvisibilitychange';
state = 'webkitVisibilityState';
}
return document[state] === 'hidden';
}
/**
* 判断当前tab页可见
* @param callback 可见回调
*/
function tabVisible(callback) {
isHidden = tabIsHidden();
document.addEventListener(changeEvent, function() {
if (!isHidden) {
if (callback) {
return callback();
}
}
}, false);
}
/**
* 设置光标位置
* @param el 元素
* @param pos 位置
*/
function setCursor(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();
}
}
/**
* 回车发送
* 回车 & CTRL 换行
* @param e 事件
* @param fn 回车事件
*/
function ctrlEnter(e, send) {
var code = e.keyCode,
tag = $(e.target),
val = tag.val(),
pos = tag.getCursorPosition(),
start = val.substring(0, pos),
end = val.substring(pos),
newVal = [start, '\n', end].join(''),
ctrlLike = e.ctrlKey || e.metaKey;
if (code !== 13) {
return;
}
if (!ctrlLike) {
e.preventDefault();
send(e);
} else {
tag.val(newVal);
setCursor(tag[0], pos + 1);
}
}
// 获取光标位置
// jquery.fn.extend
$.fn.extend({
getCursorPosition: _getCursorPosition
});
module.exports = {
ctrlEnter: ctrlEnter,
setCursor: setCursor,
tabVisible: tabVisible,
tabIsHidden: tabIsHidden
};