touch.ts 877 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. export class Touch {
  2. // 触摸起始Y坐标
  3. startY = 0;
  4. // 触摸起始X坐标
  5. startX = 0;
  6. // 横向滑动参数
  7. horizontal = 0;
  8. start(e: UniTouchEvent) {
  9. this.startX = e.touches[0].clientX;
  10. this.startY = e.touches[0].clientY;
  11. this.horizontal = 0;
  12. }
  13. move(e: UniTouchEvent) {
  14. const x = this.startX - e.touches[0].clientX;
  15. if (this.horizontal == 0) {
  16. // 只在horizontal=0时判断一次
  17. const y = this.startY - e.touches[0].clientY;
  18. if (Math.abs(x) > Math.abs(y)) {
  19. // 如果x轴移动距离大于y轴移动距离则表明是横向移动手势
  20. this.horizontal = 1;
  21. }
  22. if (this.horizontal == 1) {
  23. // 如果是横向移动手势,则阻止默认行为(防止页面滚动)
  24. e.preventDefault();
  25. }
  26. }
  27. }
  28. end() {
  29. this.startY = 0;
  30. this.horizontal = 0;
  31. }
  32. }
  33. export function useTouch(): Touch {
  34. return new Touch();
  35. }