service.ts 2.1 KB

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