1 ; (function ($, window, document, undefined) { 2 var touchMoveDirection = function (ele, opt) { 3 var $this = this; 4 $this.$element = $(ele); 5 $this._default = { 6 onLeft: null, 7 onUp: null, 8 onRight: null, 9 onDown: null 10 } 11 $this.option = $.extend({}, $this._default, opt); 12 13 $this.startX = 0; 14 $this.startY = 0; 15 $this.endX = 0; 16 $this.endY = 0; 17 $this.$element.on("touchstart", function (e) { 18 var touchPosition = e.originalEvent.targetTouches[0]; 19 $this.startX = touchPosition.pageX; 20 $this.startY = touchPosition.pageY; 21 }); 22 23 $this.$element.on("touchend", function (e) { 24 25 var touchPosition = e.originalEvent.changedTouches[0]; 26 $this.endX = touchPosition.pageX; 27 $this.endY = touchPosition.pageY; 28 29 $this.invokeDirectionCallBack(); 30 }); 31 } 32 33 touchMoveDirection.prototype = { 34 getAngle: function (angx, angy) { 35 return Math.atan2(angy, angx) * 180 / Math.PI; 36 }, 37 invokeDirectionCallBack: function () { 38 var $this = this; 39 40 var angx = $this.endX - $this.startX; 41 var angy = $this.endY - $this.startY; 42 43 //如果滑动距离太短 44 if (Math.abs(angx) < 2 && Math.abs(angy) < 2) { 45 return; 46 } 47 48 var angle = $this.getAngle(angx, angy); 49 if (-135 <= angle && angle <= -45) { 50 //Up 51 if (typeof ($this.option.onUp) == "function") { 52 $this.option.onUp(); 53 } 54 } else if (45 <= angle && angle < 135) { 55 //Down 56 if (typeof ($this.option.onDown) == "function") { 57 $this.option.onDown(); 58 } 59 } else if ((135 <= angle && angle <= 180) || (-180 <= angle && angle < -135)) { 60 //Left 61 if (typeof ($this.option.onLeft) == "function") { 62 $this.option.onLeft(); 63 } 64 } else if (-45 <= angle && angle <= 45) { 65 //Right 66 if (typeof ($this.option.onRight) == "function") { 67 $this.option.onRight(); 68 } 69 } 70 } 71 } 72 73 $.fn.touchMoveDirection = function (opt) { 74 return new touchMoveDirection(this, opt); 75 } 76 })(jQuery, window, document);
使用:
1 $("#test").touchMoveDirection({ 2 onLeft: function () { 3 console.log("left"); 4 }, 5 onUp: function () { 6 console.log("up"); 7 }, 8 onRight: function () { 9 console.log("right"); 10 }, 11 onDown: function () { 12 console.log("down"); 13 }, 14 });