欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Zepto.js touch模块深入分析

程序员文章站 2022-05-03 18:04:18
...
//	 Zepto.js
//	 (c) 2010-2015 Thomas Fuchs
//	 Zepto.js may be freely distributed under the MIT license.

;
(function($) {
  var touch = {},
    touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
    longTapDelay = 750,
    gesture
    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() {
      longTapTimeout = null
      if (touch.last) {
        touch.el.trigger('longTap')
        touch = {}
      }
    }
    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 = {}
    }
    function isPrimaryTouch(event) {
      return (event.pointerType == 'touch' ||
        event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary
    }
    function isPointerEventType(e, type) {
      return (e.type == 'pointer' + type ||
        e.type.toLowerCase() == 'mspointer' + type)
    }
  $(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) {
          touch.el.trigger('swipe')
          touch.el.trigger('swipe' + swipeDirectionFromVelocity)
        }
      })
      .on('touchstart MSPointerDown pointerdown', function(e) {
        if ((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return
        firstTouch = _isPointerType ? e : e.touches[