service.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // components/service/service.ts
  2. // 获取应用实例
  3. const app = getApp<IAppOption>()
  4. Component({
  5. /**
  6. * 组件的初始数据
  7. */
  8. data: {
  9. popShow: false,
  10. btnShow: true,
  11. maxTop: 0,
  12. top: 0, // 初始的上偏移
  13. startY: 0, // 触摸起始点 Y 坐标
  14. windowWidth: 0, // 屏幕宽度
  15. windowHeight: 0, // 屏幕高度
  16. elementHeight: 60 // 元素高度
  17. },
  18. lifetimes: {
  19. attached() {
  20. // 获取屏幕宽高
  21. const systemInfo = wx.getWindowInfo();
  22. const isAndroid = systemInfo.platform === 'android'
  23. const isDevtools = systemInfo.platform === 'devtools'
  24. const barHeight = !isAndroid ?
  25. const globalTop = app.globalData.top
  26. this.setData({
  27. windowWidth: systemInfo.windowWidth,
  28. windowHeight: systemInfo.windowHeight,
  29. top: globalTop
  30. });
  31. }
  32. },
  33. /**
  34. * 组件的方法列表
  35. */
  36. methods: {
  37. onClose() {
  38. // this.triggerEvent('changePop', false)
  39. this.setData({
  40. popShow: false
  41. })
  42. },
  43. onOpen() {
  44. //
  45. },
  46. onShow() {
  47. this.setData({
  48. popShow: true
  49. })
  50. },
  51. onTouchStart(e: any) {
  52. // 记录触摸起始点的 Y 坐标
  53. this.setData({
  54. startY: e.touches[0].clientY
  55. });
  56. },
  57. onTouchMove(e: any) {
  58. // 计算上下方向的偏移量
  59. const deltaY = e.touches[0].clientY - this.data.startY;
  60. // 更新元素的垂直位置
  61. app.globalData.top = this.data.top + deltaY
  62. this.setData({
  63. top: this.data.top + deltaY,
  64. startY: e.touches[0].clientY
  65. });
  66. },
  67. onTouchEnd() {
  68. const { top, windowHeight, elementHeight } = this.data;
  69. // 计算与顶部和底部边界的距离
  70. const distanceTop = top;
  71. const moveHeight = top + elementHeight
  72. // 判断元素与顶部和底部的距离,选择最近的边界
  73. if (distanceTop < 0) {
  74. this.setData({ top: 0 }, () => {
  75. app.globalData.top = 0
  76. }); // 吸附到顶部
  77. } else if(moveHeight >= windowHeight) {
  78. this.setData({ top: windowHeight - elementHeight }, () => {
  79. app.globalData.top = windowHeight - elementHeight
  80. })
  81. } else {
  82. this.setData({ top }, () => {
  83. app.globalData.top = top
  84. })
  85. }
  86. }
  87. }
  88. })