service.ts 2.4 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 ? 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. },
  50. onTouchStart(e: any) {
  51. // 记录触摸起始点的 Y 坐标
  52. this.setData({
  53. startY: e.touches[0].clientY
  54. });
  55. },
  56. onTouchMove(e: any) {
  57. // 计算上下方向的偏移量
  58. const deltaY = e.touches[0].clientY - this.data.startY;
  59. // 更新元素的垂直位置
  60. app.globalData.top = this.data.top + deltaY
  61. this.setData({
  62. top: this.data.top + deltaY,
  63. startY: e.touches[0].clientY
  64. });
  65. },
  66. onTouchEnd() {
  67. const { top, windowHeight, elementHeight } = this.data;
  68. // 计算与顶部和底部边界的距离
  69. const distanceTop = top;
  70. const moveHeight = top + elementHeight
  71. // 判断元素与顶部和底部的距离,选择最近的边界
  72. if (distanceTop < this.data.maxTop) {
  73. this.setData({ top: this.data.maxTop }, () => {
  74. app.globalData.top = this.data.maxTop
  75. }); // 吸附到顶部
  76. } else if(moveHeight >= windowHeight) {
  77. this.setData({ top: windowHeight - elementHeight }, () => {
  78. app.globalData.top = windowHeight - elementHeight
  79. })
  80. } else {
  81. this.setData({ top }, () => {
  82. app.globalData.top = top
  83. })
  84. }
  85. }
  86. }
  87. })