深入浅出zeptojs中tap事件

1、tap事件实现

zepto 源码里面看关于tap的实现方法:

  1 $(document).ready(function(){
  2     var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType
  3 
  4     if ('MSGesture' in window) {
  5       gesture = new MSGesture()
  6       gesture.target = document.body
  7     }
  8 
  9     $(document)
 10       .bind('MSGestureEnd', function(e){
 11         var swipeDirectionFromVelocity =
 12           e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
 13         if (swipeDirectionFromVelocity) {
 14           touch.el.trigger('swipe')
 15           touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
 16         }
 17       })
 18       .on('touchstart MSPointerDown pointerdown', function(e){
 19         if((_isPointerType = isPointerEventType(e, 'down')) &&
 20           !isPrimaryTouch(e)) return
 21         firstTouch = _isPointerType ? e : e.touches[0]
 22         if (e.touches && e.touches.length === 1 && touch.x2) {
 23           // Clear out touch movement data if we have it sticking around
 24           // This can occur if touchcancel doesn't fire due to preventDefault, etc.
 25           touch.x2 = undefined
 26           touch.y2 = undefined
 27         }
 28         now = Date.now()
 29         delta = now - (touch.last || now)
 30         touch.el = $('tagName' in firstTouch.target ?
 31           firstTouch.target : firstTouch.target.parentNode)
 32         touchTimeout && clearTimeout(touchTimeout)
 33         touch.x1 = firstTouch.pageX
 34         touch.y1 = firstTouch.pageY
 35         if (delta > 0 && delta <= 250) touch.isDoubleTap = true
 36         touch.last = now
 37         longTapTimeout = setTimeout(longTap, longTapDelay)
 38         // adds the current touch contact for IE gesture recognition
 39         if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
 40       })
 41       .on('touchmove MSPointerMove pointermove', function(e){
 42         if((_isPointerType = isPointerEventType(e, 'move')) &&
 43           !isPrimaryTouch(e)) return
 44         firstTouch = _isPointerType ? e : e.touches[0]
 45         cancelLongTap()
 46         touch.x2 = firstTouch.pageX
 47         touch.y2 = firstTouch.pageY
 48 
 49         deltaX += Math.abs(touch.x1 - touch.x2)
 50         deltaY += Math.abs(touch.y1 - touch.y2)
 51       })
 52       .on('touchend MSPointerUp pointerup', function(e){
 53         if((_isPointerType = isPointerEventType(e, 'up')) &&
 54           !isPrimaryTouch(e)) return
 55         cancelLongTap()
 56 
 57         // swipe
 58         if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
 59             (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
 60 
 61           swipeTimeout = setTimeout(function() {
 62             touch.el.trigger('swipe')
 63             touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
 64             touch = {}
 65           }, 0)
 66 
 67         // normal tap
 68         else if ('last' in touch)
 69           // don't fire tap when delta position changed by more than 30 pixels,
 70           // for instance when moving to a point and back to origin
 71           if (deltaX < 30 && deltaY < 30) {
 72             // delay by one tick so we can cancel the 'tap' event if 'scroll' fires
 73             // ('tap' fires before 'scroll')
 74             tapTimeout = setTimeout(function() {
 75 
 76               // trigger universal 'tap' with the option to cancelTouch()
 77               // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
 78               var event = $.Event('tap')
 79               event.cancelTouch = cancelAll
 80               touch.el.trigger(event)
 81 
 82               // trigger double tap immediately
 83               if (touch.isDoubleTap) {
 84                 if (touch.el) touch.el.trigger('doubleTap')
 85                 touch = {}
 86               }
 87 
 88               // trigger single tap after 250ms of inactivity
 89               else {
 90                 touchTimeout = setTimeout(function(){
 91                   touchTimeout = null
 92                   if (touch.el) touch.el.trigger('singleTap')
 93                   touch = {}
 94                 }, 250)
 95               }
 96             }, 0)
 97           } else {
 98             touch = {}
 99           }
100           deltaX = deltaY = 0
101 
102       })
103       // when the browser window loses focus,
104       // for example when a modal dialog is shown,
105       // cancel all ongoing events
106       .on('touchcancel MSPointerCancel pointercancel', cancelAll)
107 
108     // scrolling the window indicates intention of the user
109     // to scroll, not tap or swipe, so cancel all ongoing events
110     $(window).on('scroll', cancelAll)
111   })
112 
113   ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
114     'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
115     $.fn[eventName] = function(callback){ return this.on(eventName, callback) }
116   })

zepto的tap通过兼听绑定在document上的touch事件来完成tap事件的模拟的,及tap事件是冒泡到document上触发的再点击完成时的tap事件(touchstart ouchend)需要冒泡到document上才会触发,而在冒泡到document之前,用户手的接触屏幕(touchstart)和离开屏幕(touchend)是会触发click事件的,因为click事件有延迟触发(这就是为什么移动端不用click而用tap的原因)(大概是300ms,为了实现safari的双击事件的设计),所以在执行完tap事件之后,弹出来的选择组件马上就隐藏了,此时click事件还在延迟的300ms之中,当300ms到来的时候,click到的其实不是完成而是隐藏之后的下方的元素,如果正下方的元素绑定的有click事件此时便会触发,如果没有绑定click事件的话就当没click,但是正下方的是input输入框(或者select选择框或者单选复选框),点击默认聚焦而弹出输入键盘,这就是常出现的“点透”的情况。

下面一个例子看看点透是什么情况:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title></title>
 6     <style type="text/css">
 7         input {
 8             width: 200px;
 9             height: 50px;
10         }
11         .layer {
12             width: 200px;
13             height: 200px;
14             position: absolute;
15             left: 0;
16             top: 0;
17             background: red;
18             opacity: .5;
19         }
20     </style>
21 </head>
22 <body>
23 <div class="layer" id="J_layer"></div>
24 <input type="text">
25 
26 <script type="text/javascript" src="/lib/zepto.js"></script>
27 <script type="text/javascript">
28     $('#J_layer').on('tap', function () {
29         var $this = $(this);
30         $this.hide();
31     });
32 </script>
33 </body>
34 </html>

运行出来的情况是:

当点击“layer”处于“input”上方区域后出现:

上图可以看出,input获取到了焦点。

这就是点透现象,input获取到了click事件。

 2、解决“点透”问题

2.1、引入fastclick.js,因为fastclick源码不依赖其他库所以你可以在原生的js前直接加上。https://github.com/ftlabs/fastclick

1 window.addEventListener( "load", function() {
2      FastClick.attach( document.body );
3 }, false );

2.2、用touchend代替tap事件并阻止掉touchend的默认行为preventDefault()

1 $("#layer").on("touchend", function (event) {
2      //很多处理比如隐藏什么的
3      event.preventDefault();
4 });

2.3、延迟一定的时间(300ms+)来处理事件

1 $("#layer").on("tap", function (event) {
2     setTimeout(function(){
3     //程序处理
4     },320);
5 }); 

以上就是对zepto中tap方法的解说,请大家多多提问

原文地址:https://www.cnblogs.com/bo-haier/p/5650323.html