service.ts 2.4 KB

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