forked from RubyLouvre/avalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20 touch.js
339 lines (329 loc) · 13.9 KB
/
20 touch.js
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
new function() {
var ua = navigator.userAgent
var isAndroid = ua.indexOf("Android") > 0
var isIOS = /iP(ad|hone|od)/.test(ua)
var me = bindingHandlers.on
var touchProxy = {}
var IE11touch = navigator.pointerEnabled
var IE9_10touch = navigator.msPointerEnabled
var w3ctouch = (function() {
var supported = isIOS || false
//http://stackoverflow.com/questions/5713393/creating-and-firing-touch-events-on-a-touch-enabled-browser
try {
var div = document.createElement("div")
div.ontouchstart = function() {
supported = true
}
var e = document.createEvent("TouchEvent")
e.initUIEvent("touchstart", true, true)
div.dispatchEvent(e)
} catch (err) {
}
div = div.ontouchstart = null
return supported
})()
var touchSupported = !!(w3ctouch || IE11touch || IE9_10touch)
//合成做成触屏事件所需要的各种原生事件
var touchNames = ["mousedown", "mousemove", "mouseup", ""]
if (w3ctouch) {
touchNames = ["touchstart", "touchmove", "touchend", "touchcancel"]
} else if (IE11touch) {
touchNames = ["pointerdown", "pointermove", "pointerup", "pointercancel"]
} else if (IE9_10touch) {
touchNames = ["MSPointerDown", "MSPointerMove", "MSPointerUp", "MSPointerCancel"]
}
var clickbuster = {
underFrame: null,
coordinates: [],
addUnderFrame: function(event) {
var underFrame = null
if(!clickbuster.underFrame) {
underFrame = document.createElement('div');
underFrame.style.cssText = [
"opacity: 0",
"display: none;",
"border-radius: 60px;",
"position: absolute;",
"z-index: 99999;",
"width: 60px;",
"height: 60px"
].join("");
document.body.appendChild(underFrame)
}
clickbuster.underFrame = underFrame
underFrame.style.top = (event.changedTouches[0].clientY - 30) + "px"
underFrame.style.left = (event.changedTouches[0].clientX - 30) + "px"
underFrame.style.display = "block"
setTimeout(function(){
underFrame.style.display = "none"
}, 360)
},
preventGhostClick: function(x, y) {
clickbuster.coordinates.push(x, y);
window.setTimeout(clickbuster.pop, 2500)
},
pop: function() {
clickbuster.coordinates.splice(0, 2)
},
onClick: function(event) {
for (var i = 0; i < clickbuster.coordinates.length; i += 2) {
var x = clickbuster.coordinates[i]
var y = clickbuster.coordinates[i + 1]
if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
event.stopPropagation();
event.preventDefault();
}
}
}
}
if (touchSupported) {
//我们经由ms-click, ms-on-tap绑定事件, 其实没有直接绑在元素,全部放到一个数组中
//当通过touchstart, touchend等事件混合计算得当前场景应该需要执行click, tap,那么
//直接执行el["msdispatch"]方法
"click,tap".replace(/\w+/g, function(method) {
avalon.eventHooks[method] = {
type: method,
deel: function(el, type, fn, isAdd) {
var listName = "ms" + method + "list"
var fns = el[listName] || (el[listName] = [])
if (!el["msdispatch"]) {
el["msdispatch"] = function(event) {
if (event.fireByAvalon) {
for (var i = 0, fn; fn = fns[i++]; ) {
fn.call(el, event)
}
}
}
el.addEventListener(type, el["msdispatch"])
}
if (isAdd) {
fns.push(fn)
} else {
avalon.Array.remove(fns, fn)
}
fn.unbind = true
return fn
}
}
})
}
//判定滑动方向
function swipeDirection(x1, x2, y1, y2) {
return Math.abs(x1 - x2) >=
Math.abs(y1 - y2) ? (x1 - x2 > 0 ? "left" : "right") : (y1 - y2 > 0 ? "up" : "down")
}
function getCoordinates(event) {
var touches = event.touches && event.touches.length ? event.touches : [event];
var e = event.changedTouches ? event.changedTouches[0] : touches[0]
return {
x: e.clientX,
y: e.clientY
}
}
function touchend(event) {
var element = touchProxy.element
if (!element)
return
var e = getCoordinates(event)
var diff = Date.now() - touchProxy.startTime //经过时间
var totalX = Math.abs(touchProxy.x - e.x)
var totalY = Math.abs(touchProxy.y - e.y)
if (touchProxy.doubleIndex === 2 && avalon.config.stopZoom) {//如果已经点了两次,就可以触发dblclick 回调
event.preventDefault()
}
if (totalX > 30 || totalY > 30) {
//如果用户滑动的距离有点大,就认为是swipe事件
var direction = swipeDirection(touchProxy.x, e.x, touchProxy.y, e.y)
var details = {
direction: direction
}
W3CFire(element, "swipe", details)
W3CFire(element, "swipe" + direction, details)
} else {
//如果移动的距离太少,则认为是tap,click,hold,dblclick
if (fastclick.canClick(element) &&
touchProxy.mx < fastclick.dragDistance &&
touchProxy.my < fastclick.dragDistance) {
// 失去焦点的处理
if (document.activeElement && document.activeElement !== element) {
document.activeElement.blur()
}
//如果此元素不为表单元素,或者它没有disabled
var forElement
if (element.tagName.toLowerCase() === "label") {
forElement = element.htmlFor ? document.getElementById(element.htmlFor) : null
}
if (forElement) {
fastclick.focus(forElement)
} else {
fastclick.focus(element)
}
avalon.fastclick.fireEvent(element, "click", event)//触发click事件
W3CFire(element, "tap")//触发tap事件
if (forElement) {
avalon.fastclick.fireEvent(forElement, "click", event)
W3CFire(element, "tap")//触发tap事件
}
if (diff < 250) {
if (touchProxy.doubleIndex == 2) {
avalon.fastclick.fireEvent(element, "dblclick", event)//触发dblclick事件
W3CFire(element, "doubletap")//触发doubletap事件
touchProxy.doubleIndex = 0
} else {
setTimeout(function() {
touchProxy.doubleIndex = 0
}, 250)
}
}
if (diff > fastclick.clickDuration) {
W3CFire(element, "hold")
W3CFire(element, "longtap")
touchProxy.doubleIndex = 0
}
}
}
avalon(element).removeClass(fastclick.activeClass)
touchProxy.element = null
}
// 避免被点击的元素下有input、textarea时会触发其focus从而调出键盘
// http://hzxiaosheng.github.io/work/2014/09/13/click-event-300ms-delay-and-ghost-click-in-mobile-browser/
document.addEventListener('click', clickbuster.onClick, true)
document.addEventListener(touchNames[1], function(event) {
if (!touchProxy.element)
return
var e = getCoordinates(event)
touchProxy.mx += Math.abs(touchProxy.cx - e.x)
touchProxy.my += Math.abs(touchProxy.cy - e.y)
if (touchProxy.tapping && (touchProxy.mx > fastclick.dragDistance || touchProxy.my > fastclick.dragDistance)) {
touchProxy.element = null
}
})
document.addEventListener(touchNames[2], touchend)
if (touchNames[3]) {
document.addEventListener(touchNames[3], touchend)
}
me["clickHook"] = function(data) {
function touchstart(event) {
var element = data.element
avalon.mix(touchProxy, getCoordinates(event))
touchProxy.cx = touchProxy.x
touchProxy.cy = touchProxy.y
touchProxy.mx = 0 //计算总结移动了多少距离,指在移动距离重分
touchProxy.my = 0
// touchProxy.startTime = Date.now()
touchProxy.event = data.param
touchProxy.tapping = /click|tap|hold$/.test(touchProxy.event)
//--------------处理双击事件--------------
if (!touchProxy.doubleIndex) {
touchProxy.doubleIndex = 1
touchProxy.startTime = Date.now()
} else {
touchProxy.doubleIndex = 2
}
touchProxy.element = element
if (touchProxy.tapping && avalon.fastclick.canClick(element)) {
avalon(element).addClass(fastclick.activeClass)
}
}
function needFixClick(type) {
return type === "click"
}
if (needFixClick(data.param) ? touchSupported : true) {
data.specialBind = function(element, callback) {
element.addEventListener(touchNames[0], touchstart)
data.msCallback = callback
avalon.bind(element, data.param, callback)
}
data.specialUnbind = function() {
element.removeEventListener(touchNames[0], touchstart)
avalon.bind(data.element, data.param, data.msCallback)
}
}
}
//fastclick只要是处理移动端点击存在300ms延迟的问题
//这是苹果乱搞异致的,他们想在小屏幕设备上通过快速点击两次,将放大了的网页缩放至原始比例。
var fastclick = avalon.fastclick = {
activeClass: "ms-click-active",
clickDuration: 750, //小于750ms是点击,长于它是长按或拖动
dragDistance: 30, //最大移动的距离
fireEvent: function(element, type, event) {
var clickEvent = document.createEvent("MouseEvents")
clickEvent.initMouseEvent(type, true, true, window, 1, event.screenX, event.screenY,
event.clientX, event.clientY, false, false, false, false, 0, null)
Object.defineProperty(clickEvent, "fireByAvalon", {
value: true
})
element.dispatchEvent(clickEvent)
},
focus: function(target) {
if (this.canFocus(target)) {
//https://github.com/RubyLouvre/avalon/issues/254
var value = target.value
target.value = value
if (isIOS && target.setSelectionRange && target.type.indexOf("date") !== 0 && target.type !== 'time') {
// iOS 7, date datetime等控件直接对selectionStart,selectionEnd赋值会抛错
var n = value.length
target.setSelectionRange(n, n)
} else {
target.focus()
}
}
},
canClick: function(target) {
switch (target.nodeName.toLowerCase()) {
case "textarea":
case "select":
case "input":
return !target.disabled
default:
return true
}
},
canFocus: function(target) {
switch (target.nodeName.toLowerCase()) {
case "textarea":
return true;
case "select":
return !isAndroid
case "input":
switch (target.type) {
case "button":
case "checkbox":
case "file":
case "image":
case "radio":
case "submit":
return false
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly
default:
return false
}
}
};
["swipe", "swipeleft", "swiperight", "swipeup", "swipedown", "doubletap", "tap", "dblclick", "longtap", "hold"].forEach(function(method) {
me[method + "Hook"] = me["clickHook"]
})
if (touchSupported) {
me[touchNames[2] + "Hook"] = function(data) {
data.specialBind = function(element, callback) {
var _callback = callback
if (element.hasAttribute('avoidFocus')) {
_callback = function(event) {
var e = getCoordinates(event)
clickbuster.preventGhostClick(e.x, e.y)
clickbuster.addUnderFrame(event)
callback.apply(this, [].slice.call(arguments))
}
}
data.msCallback = _callback
avalon.bind(element, data.param, _callback)
}
data.specialUnbind = function() {
avalon.unbind(data.element, data.param, data.msCallback)
}
}
}
//各种摸屏事件的示意图 http://quojs.tapquo.com/ http://touch.code.baidu.com/
}