先上菜,看这个模块的最后一段代码,一看就明白。

['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'
].forEach(function(eventName) {
$.fn[eventName] = function(callback) {
return this.on(eventName, callback)
}
})
  • tap —元素tap的时候触发。
  • singleTap and doubleTap — 这一对事件可以用来检测元素上的单击和双击。(如果你不需要检测单击、双击,使用 tap 代替)。
  • longTap — 当一个元素被按住超过750ms触发。
  • swipeswipeLeftswipeRightswipeUpswipeDown — 当元素被划过时触发。(可选择给定的方向)

已经广为人知了,因为 click 事件有 200~300 ms 的延迟,为了更快的响应,最好用 Zepto 提供的 tap 事件,可是zepto的tap会点透,我想说它的设计必然会点透。

看看zepto中tap的实现,其中有个setTimeout(function(){},0)。如果我们引入了fastclick,其实元素的click会比tap要先触发,原因吗就是那个setTimeout,singleTap延迟250毫秒,这个就更慢了。fastclick写得更好,稍后再来分学习学习,然后分析分析。

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')
//可以cancelAll
event.cancelTouch = cancelAll
//触发tap
touch.el.trigger(event) // trigger double tap immediately
// 之前touchstart 里面有判断和上次点击时间的时间差
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
//延迟250毫秒
touchTimeout = setTimeout(function() {
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)

android 4.4 swipe 事件会有问题,需要再修复,不过修复也不好使,慎重!! 所以一般还是自己实现,不用zepto的。

关于点透,zepto把事件绑在document上,里面的tap没有组织冒泡,上机元素必然会触发相关事件,所以点透真是预料之中。那么解决也就简单,阻止冒泡就是了,具体怎么做,两种方式吧!!修改源码加上阻止冒泡,或者给里面元素绑定事件,手动阻止冒泡。

没啥可说的直接上代码。

;
(function($) {
//保存滑动过程中的一些数据
var touch = {},
//记录各种timeout
touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
//默认超过750毫秒就触发longTap
longTapDelay = 750,
gesture //判断滑动的方向 上下左右。首先判断x和y哪个滑动距离大,然后在根据x确定是左右,根据一确定上下
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 longTap() {
//置为null
longTapTimeout = null
if (touch.last) {
//触发touch.el的longTap
touch.el.trigger('longTap')
//重置touch对象
touch = {}
}
} //取消longTapTimeout定时器,
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout)
longTapTimeout = null
} //全部取消 重置
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout)
if (tapTimeout) clearTimeout(tapTimeout)
if (swipeTimeout) clearTimeout(swipeTimeout)
if (longTapTimeout) clearTimeout(longTapTimeout)
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
touch = {}
}
/*
* 是否为移动webkit内核的事件
*/
function isPrimaryTouch(event) {
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary
}
/*
* IE 10 和11的事件
*/
function isPointerEventType(e, type) {
return (e.type == 'pointer' + type ||
e.type.toLowerCase() == 'mspointer' + type)
}
//两次$(document) 难道开始就不能 var $d=$(document) 吗!!
$(document).ready(function() {
var now, delta, deltaX = 0,
deltaY = 0,
firstTouch, _isPointerType if ('MSGesture' in window) {
gesture = new MSGesture()
gesture.target = document.body
} $(document)
.bind('MSGestureEnd', function(e) {
var swipeDirectionFromVelocity =
e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
if (swipeDirectionFromVelocity) {
//触发元素相关事件 MSGestureEnd,不清楚是神马东西,估计就是一些奇葩特有的,IE!!!!
touch.el.trigger('swipe')
touch.el.trigger('swipe' + swipeDirectionFromVelocity)
}
})
/**
* MSPointerDown pointerdown IE10 11
* touchstart 移动Webkit
*/
.on('touchstart MSPointerDown pointerdown', function(e) {
//踢出奇葩的,不是标准webkit或者IE10 11 直接返回
if ((_isPointerType = isPointerEventType(e, 'down')) &&
!isPrimaryTouch(e)) return
//我只知道正常情况都是 e.touches[0]
firstTouch = _isPointerType ? e : e.touches[0]
//一个手指在操作
if (e.touches && e.touches.length === 1 && touch.x2) {
//重置x2 和y2
// Clear out touch movement data if we have it sticking around
// This can occur if touchcancel doesn't fire due to preventDefault, etc.
touch.x2 = undefined
touch.y2 = undefined
}
//初始触发时间
now = Date.now()
//当前的now减去上次触发时间,取得差值
//如果上次时间没有就是这次的时间, 那么delta就是0
delta = now - (touch.last || now)
//取得touch el
touch.el = $('tagName' in firstTouch.target ?
firstTouch.target : firstTouch.target.parentNode)
//touchTimeout存在即清除 清除 延迟250毫秒执行的singleTap
touchTimeout && clearTimeout(touchTimeout)
//取到开始的 pageX 、pageY 赋值给x1、y1
touch.x1 = firstTouch.pageX
touch.y1 = firstTouch.pageY //上次touchstart 和这次touchstart时间相隔在250毫秒以内,就是isDoubleTap
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
//赋值touch.last,下次触发减去这个时间,来计算是否触发doubleTap
touch.last = now //设置longtap事件
longTapTimeout = setTimeout(longTap, longTapDelay)
// adds the current touch contact for IE gesture recognition
//这个表示不懂,我们从不兼容IE
if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
})
.on('touchmove MSPointerMove pointermove', function(e) {
//touchstart、touchmove、touchend 都用到这个判断,拷贝三次,我觉得改简单封装下,虽然代码不多,但是也有必要。^_^
if ((_isPointerType = isPointerEventType(e, 'move')) &&
!isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0]
//一旦发生touchmove 就取消cancelLongTap。 我觉得应该还是有个居来判断吧!!!!比如不超过5像素也没问题
cancelLongTap()
//取得此时的pageX、pageY
touch.x2 = firstTouch.pageX
touch.y2 = firstTouch.pageY //计算出和touchstart的差值
deltaX += Math.abs(touch.x1 - touch.x2)
deltaY += Math.abs(touch.y1 - touch.y2) /**
* 修复 android 4.4 swipe 事件
* https://github.com/madrobby/zepto/issues/315#issuecomment-8386027
*/
//当页面有滚动条的时候,这个修复就啃爹了。没有滚动条倒是可以随便修复。
/*if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 10) && (touch.y2 && Math.abs(touch.y1 - touch.y2) < 10))
e.preventDefault()*/
/*if (touch.x2 && Math.abs(touch.x1 - touch.x2) > 10)
e.preventDefault()*/
})
.on('touchend MSPointerUp pointerup', function(e) {
if ((_isPointerType = isPointerEventType(e, 'up')) &&
!isPrimaryTouch(e)) return
//这个就不说了,
cancelLongTap() // swipe 默认超过就触发swipe相关事件
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
swipeTimeout = setTimeout(function() {
//触发swpie 和'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown'
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
//重置touch
touch = {}
}, 0)
// normal tap
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像素
if (deltaX < 30 && deltaY < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
// 为什么要搞个setTimeout呢,因为发生滚动的时候要取消这些事件的执行,直接执行了就取消不了了
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')
//可以cancelAll
event.cancelTouch = cancelAll
//触发tap
touch.el.trigger(event) // trigger double tap immediately
// 之前touchstart 里面有判断和上次点击时间的时间差
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
//延迟250毫秒
touchTimeout = setTimeout(function() {
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)
} else {
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)
}) ;
['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'
].forEach(function(eventName) {
$.fn[eventName] = function(callback) {
return this.on(eventName, callback)
}
})
})(Zepto)

zepto源码学习-06 touch的更多相关文章

  1. zepto源码学习-05 ajax

    学习zeptoajax之前需要先脑补下,强烈推荐此文http://www.cnblogs.com/heyuquan/archive/2013/05/13/js-jquery-ajax.html 还有A ...

  2. zepto源码学习-01-整体感知

    在公司一直做移动端的项目,偶尔会做点PC端的东西,但基本上都是和移动端打交道. 移动端嘛必须上zepto,简单介绍下Zepto:它是一个面向高级浏览器的JavaScript框架的,实现JQuery的大 ...

  3. zepto源码学习-03 $()

    在第一篇的时候提到过关于$()的用法,一个接口有很多重载,用法有很多种,总结了下,大概有一以下几种 1.$(selector,context?) 传入一个选择器返回一个zepto对象 2.$(func ...

  4. zepto源码学习-02 工具方法-详细解读

    上一篇:地址 先解决上次留下的疑问,开始看到zepto.z[0]这个东西的时候,我很是不爽,看着它都不顺眼,怎么一个zepto的实例对象var test1=$('#items');  test__pr ...

  5. zepto源码学习-04 event

    之前说完$(XXX),然后还有很多零零碎碎的东西需要去分析,结果一看代码,发现zepto的实现都相对简单,没有太多可分析的.直接略过了一些实现,直接研究Event模块,相比JQuery的事件系统,ze ...

  6. 非常适合新手的jq/zepto源码分析06 -- 事件模型

    复习下事件的有关内容: 1.现在用的绑定/删除: obj.addEventListener(type,fn,false) obj.removeEventListener(type) obj.attac ...

  7. 读Zepto源码之Touch模块

    大家都知道,因为历史原因,移动端上的点击事件会有 300ms 左右的延迟,Zepto 的 touch 模块解决的就是移动端点击延迟的问题,同时也提供了滑动的 swipe 事件. 读 Zepto 源码系 ...

  8. zepto源码--核心方法10(位置)--学习笔记

    今天基本上就是zepto学习笔记的最后一篇了,介绍一下有关位置的函数,position, offset, scrollLeft, scrollTop scrollLeft 如果所选取的包装集不存在,则 ...

  9. zepto源码--定义变量--学习笔记

    主要了解一下zepto定义的初始变量. 逐一以自己的理解解析,待到后面完全透彻理解之后,争取再写一遍zepto源码学习的文章. 其中的undefined确实不明白为什么定义这么个变量在这里. docu ...

随机推荐

  1. 关于Java基本数据类型

    Java的基本数据类型分为两大类:boolean类型和数字类型.而数值类型又分为整数类型和浮点类型.而整数类型中的字符类型也可以被单独对待. 总共是4类8种. byte类型整数在内存里占8位. -12 ...

  2. Matlb中break 和continue 语句

    有两个附加语句可以控制while 和for 循环:break 和continue 语句. break 语句可以中止循环的执行和跳到end 后面的第一句执行,而continue 只中止本次循环,然后返回 ...

  3. 解决codeforces访问慢的问题

    转载至:http://blog.csdn.net/wmx16835/article/details/38639451 前阵子打Codeforces(以下简称CF),每次比赛的时候都要等待网页刷新.不是 ...

  4. nodejs设置NODE_ENV环境变量

    看下app.js文件中的一部分代码,如下: //开发环境错误处理 // will print stacktrace if (app.get('env') === 'development') { ap ...

  5. Margin的垂直外边距问题

    做练习的时候遇到一个margin的问题,代码结构如下,给父元素body中的子元素div设置了margin:50px auto;本来我是想让子元素div距离父元素上边拉开50个像素,结果却是子元素div ...

  6. FontAwesome 奥森图标的学习

    很早之前,就看到大家在使用代码做出很漂亮的图标,但是觉得需求不是很大,所以就没有看,但是技多不压身,这次有时间来学习下. FontAwesome官方网站 1,下载文件包 里面有两个文件夹,css 和 ...

  7. 【我们都爱Paul Hegarty】斯坦福IOS8公开课个人笔记19 为Demo添加手势

    在这一话中我们将应用上一话学到的知识来为Demo添加手势识别,首先添加一个缩放的功能,其次添加一个拖动功能,使得小人的表情可以随着我们的手指改变. 首先来添加一个缩放手势的识别器,我们来到FaceVi ...

  8. 把十进制整数转换为r(r=2)进制输出(顺序栈实现)

    上周的第二个作业补上~~ 上周的要求: 1.给出顺序栈的存储结构定义. 2.完成顺序栈的基本操作函数. 1)      初始化顺序栈 2)      实现入栈和出栈操作 3)      实现取栈顶元素 ...

  9. 九度OJ 1499 项目安排 -- 动态规划

    题目地址:http://ac.jobdu.com/problem.php?pid=1499 题目描述: 小明每天都在开源社区上做项目,假设每天他都有很多项目可以选,其中每个项目都有一个开始时间和截止时 ...

  10. java.util.AbstractStringBuilder源码分析

    AbstractStringBuilder是一个抽象类,是StringBuilder和StringBuffer的父类,分析它的源码对StringBuilder和StringBuffer代码的理解有很大 ...