移动端 (基于jquery的3个)touch插件

第一个 

 

/*!
 * tap.js
 * Copyright (c) 2015 Alex Gibson 
 * https://github.com/alexgibson/tap.js/
 * Released under MIT license
 */

/* global define, module */
(function (global, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return (global.Tap = factory(global, global.document));
        });
    } else if (typeof exports === 'object') {
        module.exports = factory(global, global.document);
    } else {
        global.Tap = factory(global, global.document);
    }
}(typeof window !== 'undefined' ? window : this, function (window, document) {
    'use strict';

    function Tap(el) {
        this.el = typeof el === 'object' ? el : document.getElementById(el);
        this.moved = false; //flags if the finger has moved
        this.startX = 0; //starting x coordinate
        this.startY = 0; //starting y coordinate
        this.hasTouchEventOccured = false; //flag touch event
        this.el.addEventListener('touchstart', this, false);
        this.el.addEventListener('mousedown', this, false);
    }

    // return true if left click is in the event, handle many browsers
    Tap.prototype.leftButton = function(event) {
        // modern & preferred:  MSIE>=9, Firefox(all)
        if ('buttons' in event) {
           // https://developer.mozilla.org/docs/Web/API/MouseEvent/buttons
           return event.buttons === 1;
        } else {
           return 'which' in event ?
               // 'which' is well defined (and doesn't exist on MSIE<=8)
               // https://developer.mozilla.org/docs/Web/API/MouseEvent/which
               event.which === 1 :
               // for MSIE<=8 button is 1=left (0 on all other browsers)
               // https://developer.mozilla.org/docs/Web/API/MouseEvent/button
               event.button === 1;
        }
    };

    Tap.prototype.start = function(e) {
        if (e.type === 'touchstart') {

            this.hasTouchEventOccured = true;
            this.el.addEventListener('touchmove', this, false);
            this.el.addEventListener('touchend', this, false);
            this.el.addEventListener('touchcancel', this, false);

        } else if (e.type === 'mousedown' && this.leftButton(e)) {

            this.el.addEventListener('mousemove', this, false);
            this.el.addEventListener('mouseup', this, false);
        }

        this.moved = false;
        this.startX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
        this.startY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;
    };

    Tap.prototype.move = function(e) {
        //if finger moves more than 10px flag to cancel
        var x = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
        var y = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY;
        if (Math.abs(x - this.startX) > 10 || Math.abs(y - this.startY) > 10) {
            this.moved = true;
        }
    };

    Tap.prototype.end = function(e) {
        var evt;

        this.el.removeEventListener('touchmove', this, false);
        this.el.removeEventListener('touchend', this, false);
        this.el.removeEventListener('touchcancel', this, false);
        this.el.removeEventListener('mouseup', this, false);
        this.el.removeEventListener('mousemove', this, false);

        if (!this.moved) {
            //create custom event
            try {
                evt = new window.CustomEvent('tap', {
                    bubbles: true,
                    cancelable: true
                });
            } catch (e) {
                evt = document.createEvent('Event');
                evt.initEvent('tap', true, true);
            }

            //prevent touchend from propagating to any parent
            //nodes that may have a tap.js listener attached
            e.stopPropagation();

            // dispatchEvent returns false if any handler calls preventDefault,
            if (!e.target.dispatchEvent(evt)) {
                // in which case we want to prevent clicks from firing.
                e.preventDefault();
            }
        }
    };

    Tap.prototype.cancel = function() {
        this.hasTouchEventOccured = false;
        this.moved = false;
        this.startX = 0;
        this.startY = 0;
    };

    Tap.prototype.destroy = function() {
        this.el.removeEventListener('touchstart', this, false);
        this.el.removeEventListener('touchmove', this, false);
        this.el.removeEventListener('touchend', this, false);
        this.el.removeEventListener('touchcancel', this, false);
        this.el.removeEventListener('mousedown', this, false);
        this.el.removeEventListener('mouseup', this, false);
        this.el.removeEventListener('mousemove', this, false);
    };

    Tap.prototype.handleEvent = function(e) {
        switch (e.type) {
            case 'touchstart': this.start(e); break;
            case 'touchmove': this.move(e); break;
            case 'touchend': this.end(e); break;
            case 'touchcancel': this.cancel(e); break;
            case 'mousedown': this.start(e); break;
            case 'mouseup': this.end(e); break;
            case 'mousemove': this.move(e); break;
        }
    };

    return Tap;
}));

  

 if (!e.target.dispatchEvent(evt)) {
    e.preventDefault();
  }

  

已知Event事件对象下有一个 isTrusted 属性,是一个只读属性,是一个布尔值。当事件是由用户行为生成的时候,这个属性的值为 true ,

而当事件是由脚本创建、修改、通过 EventTarget.dispatchEvent()派发的时候,这个属性的值为 false 。

 

 

依赖jQuery 或者Zepto

<script>
(function($) {
var options, Events, Touch;
options = {
x: 20,
y: 20
};
Events = ['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'tap', 'longTap', 'drag'];
Events.forEach(function(eventName) {
$.fn[eventName] = function() {
var touch = new Touch($(this), eventName);
touch.start();
if (arguments[1]) {
options = arguments[1]
}
return this.on(eventName, arguments[0])
}
});
Touch = function() {
var status, ts, tm, te;
this.target = arguments[0];
this.e = arguments[1]
};
Touch.prototype.framework = function(e) {
e.preventDefault();
var events;
if (e.changedTouches) events = e.changedTouches[0];
else events = e.originalEvent.touches[0];
return events
};
Touch.prototype.start = function() {
var self = this;
self.target.on("touchstart",
function(event) {
event.preventDefault();
var temp = self.framework(event);
var d = new Date();
self.ts = {
x: temp.pageX,
y: temp.pageY,
d: d.getTime()
}
});
self.target.on("touchmove",
function(event) {
event.preventDefault();
var temp = self.framework(event);
var d = new Date();
self.tm = {
x: temp.pageX,
y: temp.pageY
};
if (self.e == "drag") {
self.target.trigger(self.e, self.tm);
return
}
});
self.target.on("touchend",
function(event) {
event.preventDefault();
var d = new Date();
if (!self.tm) {
self.tm = self.ts
}
self.te = {
x: self.tm.x - self.ts.x,
y: self.tm.y - self.ts.y,
d: (d - self.ts.d)
};
self.tm = undefined;
self.factory()
})
};
Touch.prototype.factory = function() {
var x = Math.abs(this.te.x);
var y = Math.abs(this.te.y);
var t = this.te.d;
var s = this.status;
if (x < 5 && y < 5) {
if (t < 300) {
s = "tap"
} else {
s = "longTap"
}
} else if (x < options.x && y > options.y) {
if (t < 250) {
if (this.te.y > 0) {
s = "swipeDown"
} else {
s = "swipeUp"
}
} else {
s = "swipe"
}
} else if (y < options.y && x > options.x) {
if (t < 250) {
if (this.te.x > 0) {
s = "swipeLeft"
} else {
s = "swipeRight"
}
} else {
s = "swipe"
}
}
if (s == this.e) {
this.target.trigger(this.e);
return
}
}
})(window.jQuery || window.Zepto);


</script>

 

--------------------------------------------------------------------------------------------

第二个 作者未知(依赖jquery)

 

<script>
;(function(a){
    a.fn.touchwipe=function(c){
        var b={
            drag:false,
            min_move_x:20,
            min_move_y:20,
            wipeLeft:function(){/*向左滑动*/},
            wipeRight:function(){/*向右滑动*/},
            wipeUp:function(){/*向上滑动*/},
            wipeDown:function(){/*向下滑动*/},
            wipe:function(){/*点击*/},
            wipehold:function(){/*触摸保持*/},
            wipeDrag:function(x,y){/*拖动*/},
            preventDefaultEvents:true
        };
        if(c){a.extend(b,c)};
        this.each(function(){
            var h,g,j=false,i=false,e;
            var supportTouch = "ontouchstart" in document.documentElement;
            var moveEvent = supportTouch ? "touchmove" : "mousemove",
            startEvent = supportTouch ? "touchstart" : "mousedown",
            endEvent = supportTouch ? "touchend" : "mouseup"
             
             
            /* 移除 touchmove 监听 */
            function m(){
                this.removeEventListener(moveEvent,d);
                h=null;
                j=false;
                clearTimeout(e)
            };
             
            /* 事件处理方法 */
            function d(q){
                if(b.preventDefaultEvents){
                    q.preventDefault()
                };
                if(j){
                    var n = supportTouch ? q.touches[0].pageX : q.pageX;
                    var r = supportTouch ? q.touches[0].pageY : q.pageY;
                    var p = h-n;
                    var o = g-r;
                    if(b.drag){
                        h = n;
                        g = r;
                        clearTimeout(e);
                        b.wipeDrag(p,o);
                    }
                    else{
                        if(Math.abs(p)>=b.min_move_x){
                            m();
                            if(p>0){b.wipeLeft()}
                            else{b.wipeRight()}
                        }
                        else{
                            if(Math.abs(o)>=b.min_move_y){
                                m();
                                if(o>0){b.wipeUp()}
                                else{b.wipeDown()}
                            }
                        }
                    }
                }
            };
             
            /*wipe 处理方法*/
            function k(){clearTimeout(e);if(!i&&j){b.wipe()};i=false;j=false;};
            /*wipehold 处理方法*/
            function l(){i=true;b.wipehold()};
             
            function f(n){
                //if(n.touches.length==1){
                    h = supportTouch ? n.touches[0].pageX : n.pageX;
                    g = supportTouch ? n.touches[0].pageY : n.pageY;
                    j=true;
                    this.addEventListener(moveEvent,d,false);
                    e=setTimeout(l,750)
                //}
            };
             
            //if("ontouchstart"in document.documentElement){
                this.addEventListener(startEvent,f,false);
                this.addEventListener(endEvent,k,false)
            //}
        });
        return this
    };
})(jQuery);
 
/*
     调用
*/
$("#aa").touchwipe({
            wipeLeft:function(){ alert("向左滑动了")},
            wipeRight:function(){alert("向右滑动了")},
})
</script>

 

----------------------------------------------------------------------------------------------------------------

第三个

<script>
/**
 * jQuery Plugin to obtain touch gestures
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010)
 */
;(function($, undefined){
   $.fn.touchwipe = function(settings) {
     var config = {
            min_move_x: 50,
            min_move_y: 20,
            wipeLeft: function() { },
            wipeRight: function() { },
            preventDefaultEvents: false
     };
     
     if (settings) $.extend(config, settings);
 
     this.each(function() {
         var startX;
         var startY;
         var isMoving = false;
         var directionLocked = null;

         function cancelTouch() {
             this.removeEventListener('touchmove', onTouchMove);
             startX = null;
             isMoving = false;
             directionLocked = false;
         }  
         
         function onTouchMove(e) {
             if(config.preventDefaultEvents) {
                 e.preventDefault();
             }
             if(isMoving) {
                 var x = e.changedTouches ? e.changedTouches[0].clientX: e.clientX;
                 var y = e.changedTouches ? e.changedTouches[0].clientY: e.clientY;
                 var dx = startX - x;
                 var dy = startY - y;
                 
                var absDistX = Math.abs(dx);
                var absDistY = Math.abs(dy);

                if (directionLocked === "y") {
                    return
                } else {
                    if (directionLocked === "x") {
                        e.preventDefault()
                    } else {
                        absDistX = Math.abs(dx);
                        absDistY = Math.abs(dy);
                        if (absDistX < 4) {
                            return
                        }
                        if (absDistY > absDistX ) {
                            dx = 0;
                            directionLocked = "y";
                            return
                        } else {
                            e.preventDefault();
                            directionLocked = "x"
                        }
                    }
                }

                if(absDistX >= config.min_move_x) {
                    cancelTouch();
                    if(dx > 0) {
                        config.wipeLeft();
                    }
                    else {
                        config.wipeRight();
                    }
                 }
             }
         }
         
         function onTouchStart(e)
         {
             if (e.touches.length == 1) {
                 startX = e.changedTouches ? e.changedTouches[0].clientX: e.clientX;
                 startY = e.changedTouches ? e.changedTouches[0].clientY: e.clientY;
                 isMoving = true;
                 directionLocked = false;
                 this.addEventListener('touchmove', onTouchMove, false);
             }
         }       
         if ('ontouchstart' in document.documentElement) {
             this.addEventListener('touchstart', onTouchStart, false);
         }
     });
 
     return this;
   };
 })(jQuery);


其他地方

// JavaScript Document
 //$("#domid").tap(function(){ alert("You tapped me! -- by"+this.innerText); }); 依赖jquery 1.7+
$.fn.tap = function(e) {
    var g = this
      , a = "ontouchend" in document.createElement("div")
      , f = a ? "touchstart" : "mousedown"
      , c = a ? "touchmove" : "mousemove"
      , d = a ? "touchend" : "mouseup"
      , b = a ? "touchcancel" : "mouseout";
    g.each(function() {
        var h = {};
        h.target = this;
        $(h.target).on(f, function(j) {
            var i = "touches" in j ? j.touches[0] : (a ? window.event.touches[0] : window.event);
            h.startX = i.clientX;
            h.startY = i.clientY;
            h.endX = i.clientX;
            h.endY = i.clientY;
            h.startTime = +new Date
        }
        );
        $(h.target).on(c, function(j) {
            var i = "touches" in j ? j.touches[0] : (a ? window.event.touches[0] : window.event);
            h.endX = i.clientX;
            h.endY = i.clientY
        }
        );
        $(h.target).on(d, function(i) {
            if ((+new Date) - h.startTime < 300) {
                if (Math.abs(h.endX - h.startX) + Math.abs(h.endY - h.startY) < 20) {
                    var i = i || window.event;
                    i.preventDefault();
                    e.call(h.target)
                }
            }
            h.startTime = undefined;
            h.startX = undefined;
            h.startY = undefined;
            h.endX = undefined;
            h.endY = undefined
        }
        )
    }
    );
    return g
}
;

 

posted @ 2015-05-14 14:10  surfaces  阅读(2579)  评论(0)    收藏  举报