1.所有的touch事件都绑定在了document上,事件都是在document元素的touchend处理中触发
var now, delta, touch = {};
$(document)
.on('touchstart', startListener)
.on('touchmove', moveListener)
.on('touchend', endListener);
2.通过时间间隔判断,是双击还是单击。
每次touchstart时,都会记录一个当前的时间now,两次点击的时间差如果小于250ms,则是双击。
为什么要小于250ms呢? ---Q1
function startListener(e){
now = Date.now();
delta = now - (touch.last || now);
if ( delta > 0 && delta <= 250 ) {
// 手指连续轻触两次,时间间隔大于0,小于等于.25s,则为双击,反之单击
touch.isDoubleTap = true;
}
touch.last = now;
}
3.处理长按
var longTapTimeout, longTapDelay = 750;
function longTap() {
longTapTimeout = null
if (touch.last) {
touch.el.trigger('longTap')
touch = {}
}
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout)
longTapTimeout = null
}
function startListener(e){
// 默认就是长按,如果手指未移动和离开,超过.75s就触发longTap
longTapTimeout = setTimeout(longTap, longTapDelay)
}
function moveListener(e){
// 如果手指轻触屏幕后未超过.75s,则取消手指长按监听
cancelLongTap()
}
function endListener(e){
// 如果手指轻触屏幕后未超过.75s,则取消手指长按监听
cancelLongTap()
}
4.判断是滑动(swipe)还是轻触(tap)
// 如果手指移动屏幕超过30像素,则触发相应的滑动事件,swipeLeft, swipeRight, swipeUp, swipeDown
function endListener(e){
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) {
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch = {}
}, 0);
}
else {
// handle tap
// 关于处理tap事件,请看第5点
}
}
5.tap的相关处理(signleTap,doubleTap)
5.1 触发tap的条件
I.条件1:手指在同一方向上移动不超过30像素
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) {
// swipe
}
else {
// tap
}
II.条件2:如果手指滑动屏幕后又滑动到起始点,
!Math.abs(touch.x1 - touch.x2) > 30) === !Math.abs(touch.y1 - touch.y2) > 30) === true;
为了不触发tap事件,又添加了限制条件:
if (deltaX < 30 && deltaY < 30) {
// handle tap
}
dexltaX,dexltaY不等于起始点和终点的位移的绝对值
deltaX 不等于Math.abs(touch.x1 - touch.x2);
deltaY 不等于Math.abs(touch.y1 - touch.y2);
dexltaX,dexltaY等于起始点和终点的路程
touch.x2 = firstTouch.pageX
touch.y2 = firstTouch.pageY
deltaX += Math.abs(touch.x1 - touch.x2)
deltaY += Math.abs(touch.y1 - touch.y2)
5.2 处理tap,doubleTap,singleTap
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout)
if (tapTimeout) clearTimeout(tapTimeout)
if (swipeTimeout) clearTimeout(swipeTimeout)
if (longTapTimeout) clearTimeout(longTapTimeout)
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
// 这句很重要,将影响所有需要对touch对象属性判断的语句
touch = {}
}
function endListener(e){
tapTimeout = setTimeout(function() {
var event = $.Event('tap')
// tap事件对象event可以取消后续绑定的doubleTap, singleTap处理器
event.cancelTouch = cancelAll
touch.el.trigger(event)
// 立即触发双击事件
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}
// 定时.25s后再触发单击事件
else {
touchTimeout = setTimeout(function() {
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)
}
如何在tap事件处理器中取消doubleTap或singlerTap事件监听器
$('body')
.on('tap', function(e){
console.log('tap');
// 执行下面语句将影响是否触发绑定的 doubleTap或singleTap 处理器
e.cancelTouch();
})
.on('doubleTap', function(e){
console.log('doubleTap');
})
.on('singleTap', function(e){
console.log('singleTap');
});
// 'tap'
6、兼容指针事件系统
// 判断是否是指针事件类型
function isPointerEventType(e, type) {
return (e.type == 'pointer' + type ||
e.type.toLowerCase() == 'mspointer' + type)
}
// 判断是否是第一个touch或pointer事件对象
function isPrimaryTouch(event) {
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary
}
// 如果是指针类型是 pointerdown 或 pointermove 或 pointerup 且 不是第一个touch 或 pointer 事件对象,返回空,
// 直接屏蔽了第二个、第三...的触摸处理
if ((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return
if ((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return
if ((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return
7、快捷注册事件,touch.js为每一个实例对象注册了swipe, tap等事件:
['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'
].forEach(function(eventName) {
$.fn[eventName] = function(callback) {
return this.on(eventName, callback)
}
});
8.可以用 on 方法注册事件,也可以快捷注册
$('body').on('tap', function(){ console.log('body trigger tap event'); });
$('body').tap(function(){ console.log('body trigger tap event'); });
最后,为大家附上源码:
//表示DOMContentLoaded事件
$(document).ready(function(){
var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType
//window是否存在MSGesture对象。MSGesture提供了一些方法和属性代表页面的一系列交互,如touch,mouse,pen等。详见IE浏览器https://msdn.microsoft.com/en-us/library/windows/apps/hh968035.aspx
if ('MSGesture' in window) {
gesture = new MSGesture()
gesture.target = document.body
//target表示:你想要触发MSGestureEvents的Element对象
}
$(document)
//手势完全被处理的时候触发
.bind('MSGestureEnd', function(e){
var swipeDirectionFromVelocity =
//velocityX,velocityY用于判断元素的移动方向
e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
if (swipeDirectionFromVelocity) {
//触发swipe事件
touch.el.trigger('swipe')
touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
}
})
//触摸开始touchstart,MSPointerDown,pointerdown
.on('touchstart MSPointerDown pointerdown', function(e){
if((_isPointerType = isPointerEventType(e, 'down')) &&
!isPrimaryTouch(e)) return
//如果是往下移动,但是不是isPrimaryTouch那么我们不作处理
firstTouch = _isPointerType ? e : e.touches[0]
//touches:当前位于屏幕上的所有手指的列表。
if (e.touches && e.touches.length === 1 && touch.x2) {
// Clear out touch movement data if we have it sticking around
// This can occur if touchcancel doesn't fire due to preventDefault, etc.
//清除touchmove的数据,一般当touchcancel没有触发的时候调用(例如,preventDefault)
touch.x2 = undefined
touch.y2 = undefined
}
now = Date.now()
delta = now - (touch.last || now)
touch.el = $('tagName' in firstTouch.target ?
firstTouch.target : firstTouch.target.parentNode)
//触摸的事件的target表示当前的Element对象,如果当前对象不是Element对象,那么就获取parentNode对象
touchTimeout && clearTimeout(touchTimeout)
touch.x1 = firstTouch.pageX
touch.y1 = firstTouch.pageY
//x1,y1存储的是pageX,pageY属性
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
//如果两次触屏在[0,250]表示双击
touch.last = now
longTapTimeout = setTimeout(longTap, longTapDelay)
//这里是长按
// adds the current touch contact for IE gesture recognition
if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
//如果是IE浏览器,为new MSGesture()对象添加一个Pointer对象,传入的是我们的event对象的pointerId的值
//把元素上的一个触点添加到MSGesture对象上!
})
.on('touchmove MSPointerMove pointermove', function(e){
if((_isPointerType = isPointerEventType(e, 'move')) &&
!isPrimaryTouch(e)) return
firstTouch = _isPointerType ? e : e.touches[0]
//这时候我们取消长按的事件处理程序,因为这里是pointermove,也就是手势移动了那么肯定不会是长按了
//但是因为我们在pointerdown中不知道是否是长按还是pointermove,所以才默认使用的长按。如果移动了,那么就知道不是长按了
cancelLongTap()
touch.x2 = firstTouch.pageX
touch.y2 = firstTouch.pageY
deltaX += Math.abs(touch.x1 - touch.x2)
deltaY += Math.abs(touch.y1 - touch.y2)
//得到两者在X和Y方向移动的绝对距离
})
.on('touchend MSPointerUp pointerup', function(e){
if((_isPointerType = isPointerEventType(e, 'up')) &&
!isPrimaryTouch(e)) return
//触摸结束,这时候我们取消掉长按的定时器,因为我们也已经知道不是长按了,所以取消长按的定时器
cancelLongTap()
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
//如果任意一方向移动的距离大于30,那么表示触发swipe事件。触发了swipe事件后,我们清除touch列表,也就是设置为touch={}
//因为移动结束了,那么必须重置为空
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch = {}
}, 0)
// normal tap
//这里是正常的tap事件,last表示上一次点击的时间,也就是说已经发生了点击了
//last属性是在touchstart中进行赋值的,因此如果存在那么表示已经点击过了
//但是不管是双击还是单击都会运行到这里的代码!!!
else if ('last' in touch)
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
//如果移动距离超过30那么我们不会触发tap事件,因为触摸事件不是移动,不能让他移动了30px了
if (deltaX < 30 && deltaY < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
//tap事件是在scroll之前,所以如果scroll了那么我们取消tap事件
tapTimeout = setTimeout(function() {
// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.Event('tap')
event.cancelTouch = cancelAll
touch.el.trigger(event)
//tap会立即触发
// trigger double tap immediately
//如果是双击,那么我们立即触发doubleTap事件,这时候我们的touch={}那么后面的singleTap是不会执行的
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}
// trigger single tap after 250ms of inactivity
//如果不是双击,那么此时tap已经触发了,等待250ms我们再次触发singleTap事件
else {
touchTimeout = setTimeout(function(){
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
//情况touch对象,因为手指已经离开屏幕了
}, 250)
}
}, 0)
} else {
touch = {}
}
//注意:不管是singleTap还是doubleTap,swipe,调用后都会清空touch={},也就是这时候是重新开始的触摸事件了
deltaX = deltaY = 0
})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
//触摸被取消(触摸被一些事情中断,比如通知)
.on('touchcancel MSPointerCancel pointercancel', cancelAll)
// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
$(window).on('scroll', cancelAll)
})
补充:
问题:当在移动设备上“快速滑动”或者“划出屏幕外”时,第一次tap不会触发,第二次tap才会触发。
原因:因为touchend事件没出发,deltaX和deltaY没有被置0,下次点击时deltaX或deltaY的值大于30,导致tap没有被触发。
解决方法:在touchstart时,将deltaX和deltaY置0
.on('touchstart MSPointerDown pointerdown', function(e){
deltaX = deltaY = 0;
……