touch.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const MIN_DISTANCE = 10
  2. function getDirection(x, y) {
  3. if (x > y && x > MIN_DISTANCE) {
  4. return 'horizontal'
  5. }
  6. if (y > x && y > MIN_DISTANCE) {
  7. return 'vertical'
  8. }
  9. return ''
  10. }
  11. export default {
  12. methods: {
  13. touchStart(e) {
  14. this.resetTouchStatus()
  15. const touch = this.getTouchPoint(e)
  16. this.startX = touch.x
  17. this.startY = touch.y
  18. },
  19. touchMove(e) {
  20. const touch = this.getTouchPoint(e)
  21. this.deltaX = touch.x - this.startX
  22. this.deltaY = touch.y - this.startY
  23. this.offsetX = Math.abs(this.deltaX)
  24. this.offsetY = Math.abs(this.deltaY)
  25. this.direction = this.direction || getDirection(this.offsetX, this.offsetY)
  26. },
  27. getTouchPoint(e) {
  28. if (!e) {
  29. return {
  30. x: 0,
  31. y: 0
  32. }
  33. }
  34. if (e.touches && e.touches[0]) {
  35. return {
  36. x: e.touches[0].pageX,
  37. y: e.touches[0].pageY
  38. }
  39. }
  40. if (e.changedTouches && e.changedTouches[0]) {
  41. return {
  42. x: e.changedTouches[0].pageX,
  43. y: e.changedTouches[0].pageY
  44. }
  45. }
  46. return {
  47. x: e.clientX || 0,
  48. y: e.clientY || 0
  49. }
  50. },
  51. resetTouchStatus() {
  52. this.direction = ''
  53. this.deltaX = 0
  54. this.deltaY = 0
  55. this.offsetX = 0
  56. this.offsetY = 0
  57. }
  58. }
  59. }