service.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 ? 44 : 48;
  25. const globalTop = app.globalData.top
  26. this.setData({
  27. maxTop: barHeight + systemInfo.safeArea.top,
  28. windowWidth: systemInfo.windowWidth,
  29. windowHeight: systemInfo.windowHeight,
  30. top: globalTop
  31. });
  32. }
  33. },
  34. /**
  35. * 组件的方法列表
  36. */
  37. methods: {
  38. onClose() {
  39. // this.triggerEvent('changePop', false)
  40. this.setData({
  41. popShow: false
  42. })
  43. },
  44. onOpen() {
  45. //
  46. },
  47. onShow() {
  48. // this.triggerEvent('openService')
  49. this.setData({
  50. popShow: true
  51. })
  52. },
  53. onTouchStart(e: any) {
  54. // 记录触摸起始点的 Y 坐标
  55. this.setData({
  56. startY: e.touches[0].clientY
  57. });
  58. },
  59. onTouchMove(e: any) {
  60. // 计算上下方向的偏移量
  61. const deltaY = e.touches[0].clientY - this.data.startY;
  62. // 更新元素的垂直位置
  63. app.globalData.top = this.data.top + deltaY
  64. this.setData({
  65. top: this.data.top + deltaY,
  66. startY: e.touches[0].clientY
  67. });
  68. },
  69. onTouchEnd() {
  70. const { top, windowHeight, elementHeight } = this.data;
  71. // 计算与顶部和底部边界的距离
  72. const distanceTop = top;
  73. const moveHeight = top + elementHeight
  74. // 判断元素与顶部和底部的距离,选择最近的边界
  75. if (distanceTop < this.data.maxTop) {
  76. this.setData({ top: this.data.maxTop }, () => {
  77. app.globalData.top = this.data.maxTop
  78. }); // 吸附到顶部
  79. } else if(moveHeight >= windowHeight) {
  80. this.setData({ top: windowHeight - elementHeight }, () => {
  81. app.globalData.top = windowHeight - elementHeight
  82. })
  83. } else {
  84. this.setData({ top }, () => {
  85. app.globalData.top = top
  86. })
  87. }
  88. }
  89. }
  90. })