touch-events-preventDefault.uvue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <template>
  2. <view style="flex: 1;">
  3. <page-head title="横向滑动时阻止默认事件,即阻止页面滚动"></page-head>
  4. <view class="uni-padding-wrap uni-common-mt" style="height: 40px; align-items: center;">
  5. <text>手势方向:{{direction}}</text>
  6. </view>
  7. <scroll-view style="flex: 1;" @scroll="onScroll">
  8. <view v-for="item in 120" :key="item" class="box" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend">
  9. {{item}}
  10. </view>
  11. </scroll-view>
  12. </view>
  13. </template>
  14. <script setup>
  15. const scrollTop = reactive({
  16. value: 0
  17. })
  18. defineExpose({
  19. scrollTop
  20. })
  21. function getDirection(x : number, y : number) {
  22. if (x > y && x > 10) {
  23. return 'horizontal';
  24. }
  25. if (y > x && y > 10) {
  26. return 'vertical';
  27. }
  28. return '';
  29. }
  30. const startX = ref(0)
  31. const startY = ref(0)
  32. const direction = ref("")
  33. function touchstart(e : UniTouchEvent) {
  34. direction.value = ""
  35. startX.value = e.touches[0].clientX
  36. startY.value = e.touches[0].clientY
  37. }
  38. function touchend(e : UniTouchEvent) {
  39. console.log('>>>>> touchend')
  40. direction.value = ""
  41. }
  42. function touchmove(e : UniTouchEvent) {
  43. const deltaX = e.touches[0].clientX - startX.value
  44. const deltaY = e.touches[0].clientY - startY.value
  45. if (direction.value == "") {
  46. direction.value = getDirection(Math.abs(deltaX), Math.abs(deltaY))
  47. }
  48. //只有横向滑动时才阻止默认事件,即阻止页面滚动
  49. if (direction.value != 'horizontal') {
  50. return
  51. }
  52. if (e.cancelable) {
  53. e.preventDefault()
  54. }
  55. }
  56. function onScroll(e: UniScrollEvent) {
  57. console.log('>>>>> onScroll', e.detail.scrollTop)
  58. scrollTop["value"] = e.detail.scrollTop
  59. }
  60. </script>
  61. <style scoped>
  62. .box {
  63. border-bottom: 1px solid #c6d1c3;
  64. padding: 16px 10px;
  65. }
  66. </style>