service.ts 2.2 KB

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