_swipe.jquery.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. (function($) {
  2. var Swipe = function(el) {
  3. var self = this;
  4. this.el = $(el);
  5. this.pos = { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } };
  6. this.startTime;
  7. el.on('touchstart', function(e) { self.touchStart(e); });
  8. el.on('touchmove', function(e) { self.touchMove(e); });
  9. el.on('touchend', function(e) { self.swipeEnd(); });
  10. el.on('mousedown', function(e) { self.mouseDown(e); });
  11. };
  12. Swipe.prototype = {
  13. touchStart: function(e) {
  14. var touch = e.originalEvent.touches[0];
  15. this.swipeStart(e, touch.pageX, touch.pageY);
  16. },
  17. touchMove: function(e) {
  18. var touch = e.originalEvent.touches[0];
  19. this.swipeMove(e, touch.pageX, touch.pageY);
  20. },
  21. mouseDown: function(e) {
  22. var self = this;
  23. this.swipeStart(e, e.pageX, e.pageY);
  24. this.el.on('mousemove', function(e) { self.mouseMove(e); });
  25. this.el.on('mouseup', function() { self.mouseUp(); });
  26. },
  27. mouseMove: function(e) {
  28. this.swipeMove(e, e.pageX, e.pageY);
  29. },
  30. mouseUp: function(e) {
  31. this.swipeEnd(e);
  32. this.el.off('mousemove');
  33. this.el.off('mouseup');
  34. },
  35. swipeStart: function(e, x, y) {
  36. this.pos.start.x = x;
  37. this.pos.start.y = y;
  38. this.pos.end.x = x;
  39. this.pos.end.y = y;
  40. this.startTime = new Date().getTime();
  41. this.trigger('swipeStart', e);
  42. },
  43. swipeMove: function(e, x, y) {
  44. this.pos.end.x = x;
  45. this.pos.end.y = y;
  46. this.trigger('swipeMove', e);
  47. },
  48. swipeEnd: function(e) {
  49. this.trigger('swipeEnd', e);
  50. },
  51. trigger: function(e, originalEvent) {
  52. var self = this;
  53. var
  54. event = $.Event(e),
  55. x = self.pos.start.x - self.pos.end.x,
  56. y = self.pos.end.y - self.pos.start.y,
  57. radians = Math.atan2(y, x),
  58. direction = 'up',
  59. distance = Math.round(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))),
  60. angle = Math.round(radians * 180 / Math.PI),
  61. speed = Math.round(distance / ( new Date().getTime() - self.startTime ) * 1000);
  62. if ( angle < 0 ) {
  63. angle = 360 - Math.abs(angle);
  64. }
  65. if ( ( angle <= 45 && angle >= 0 ) || ( angle <= 360 && angle >= 315 ) ) {
  66. direction = 'left';
  67. } else if ( angle >= 135 && angle <= 225 ) {
  68. direction = 'right';
  69. } else if ( angle > 45 && angle < 135 ) {
  70. direction = 'down';
  71. }
  72. event.originalEvent = originalEvent;
  73. event.swipe = { x: x, y: y, direction: direction, distance: distance, angle: angle, speed: speed };
  74. $(self.el).trigger(event);
  75. }
  76. };
  77. $.fn.swipe = function() {
  78. var swipe = new Swipe(this);
  79. return this;
  80. };
  81. })(jQuery);