sticky.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //吸顶容器组件
  2. Component({
  3. externalClasses: ['tui-sticky-class'], //自定义样式
  4. options: {
  5. multipleSlots: true
  6. },
  7. properties: {
  8. scrollTop: {
  9. type: Number,
  10. observer(val) {
  11. this.updateStickyChange();
  12. }
  13. },
  14. //吸顶容器距离顶部距离 px
  15. stickyTop: {
  16. type: Number,
  17. value: 0
  18. },
  19. //吸顶容器 高度 rpx
  20. stickyHeight: {
  21. type: String,
  22. value: "auto"
  23. },
  24. //占位容器背景颜色
  25. bgColor: {
  26. type: String,
  27. value: "none"
  28. },
  29. //列表中的索引值
  30. index: {
  31. type: Number,
  32. value: 0
  33. }
  34. },
  35. data: {
  36. timer: null,
  37. top: 0,
  38. height: 0,
  39. isFixed: false
  40. },
  41. lifetimes: {
  42. ready: function() {
  43. //在组件在视图层布局完成后执行
  44. this.updateScrollChange()
  45. },
  46. moved: function() {
  47. //在组件实例被移动到节点树另一个位置时执行
  48. this.updateScrollChange()
  49. },
  50. detached: function() {
  51. //在组件实例被从页面节点树移除时执行
  52. this.updateScrollChange()
  53. }
  54. },
  55. methods: {
  56. updateStickyChange() {
  57. const data = this.data;
  58. const top = data.top;
  59. const height = data.height;
  60. const scrollTop = this.data.scrollTop
  61. let stickyTop = this.data.stickyTop
  62. stickyTop = stickyTop < 0 ? 0 : stickyTop
  63. this.setData({
  64. isFixed: (scrollTop + stickyTop >= top && scrollTop + stickyTop < top + height) ? true : false
  65. }, () => {
  66. })
  67. },
  68. updateScrollChange() {
  69. if (this.data.timer) {
  70. clearTimeout(this.data.timer)
  71. this.setData({
  72. timer: null
  73. })
  74. }
  75. this.data.timer = setTimeout(() => {
  76. const className = '.tui-sticky-class';
  77. const query = wx.createSelectorQuery().in(this);
  78. query.select(className).boundingClientRect((res) => {
  79. if (res) {
  80. this.setData({
  81. top: res.top + (this.data.scrollTop || 0),
  82. height: res.height
  83. })
  84. this.triggerEvent('change', {
  85. index: Number(this.data.index),
  86. top: res.top + (this.data.scrollTop || 0)
  87. })
  88. }
  89. }).exec()
  90. }, 0)
  91. this.setData({
  92. timer: this.data.timer
  93. })
  94. }
  95. }
  96. });