index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import { VantComponent } from '../common/component';
  2. import { pageScrollMixin } from '../mixins/page-scroll';
  3. const ROOT_ELEMENT = '.van-sticky';
  4. VantComponent({
  5. props: {
  6. zIndex: {
  7. type: Number,
  8. value: 99,
  9. },
  10. offsetTop: {
  11. type: Number,
  12. value: 0,
  13. observer: 'onScroll',
  14. },
  15. disabled: {
  16. type: Boolean,
  17. observer: 'onScroll',
  18. },
  19. container: {
  20. type: null,
  21. observer: 'onScroll',
  22. },
  23. scrollTop: {
  24. type: null,
  25. observer(val) {
  26. this.onScroll({ scrollTop: val });
  27. },
  28. },
  29. },
  30. mixins: [
  31. pageScrollMixin(function (event) {
  32. if (this.data.scrollTop != null) {
  33. return;
  34. }
  35. this.onScroll(event);
  36. }),
  37. ],
  38. data: {
  39. height: 0,
  40. fixed: false,
  41. transform: 0,
  42. },
  43. mounted() {
  44. this.onScroll();
  45. },
  46. methods: {
  47. onScroll(obj) {
  48. obj = obj||{}
  49. let scrollTop = obj.scrollTop
  50. const { container, offsetTop, disabled } = this.data;
  51. if (disabled) {
  52. this.setDataAfterDiff({
  53. fixed: false,
  54. transform: 0,
  55. });
  56. return;
  57. }
  58. this.scrollTop = scrollTop || this.scrollTop;
  59. if (typeof container === 'function') {
  60. Promise.all([this.getRect(ROOT_ELEMENT), this.getContainerRect()]).then(
  61. ([root, container]) => {
  62. if (offsetTop + root.height > container.height + container.top) {
  63. this.setDataAfterDiff({
  64. fixed: false,
  65. transform: container.height - root.height,
  66. });
  67. } else if (offsetTop >= root.top) {
  68. this.setDataAfterDiff({
  69. fixed: true,
  70. height: root.height,
  71. transform: 0,
  72. });
  73. } else {
  74. this.setDataAfterDiff({ fixed: false, transform: 0 });
  75. }
  76. }
  77. );
  78. return;
  79. }
  80. this.getRect(ROOT_ELEMENT).then((root) => {
  81. if (offsetTop >= root.top) {
  82. this.setDataAfterDiff({ fixed: true, height: root.height });
  83. this.transform = 0;
  84. } else {
  85. this.setDataAfterDiff({ fixed: false });
  86. }
  87. });
  88. },
  89. setDataAfterDiff(data) {
  90. wx.nextTick(() => {
  91. const diff = Object.keys(data).reduce((prev, key) => {
  92. if (data[key] !== this.data[key]) {
  93. prev[key] = data[key];
  94. }
  95. return prev;
  96. }, {});
  97. this.setData(diff);
  98. this.$emit('scroll', {
  99. scrollTop: this.scrollTop,
  100. isFixed: data.fixed || this.data.fixed,
  101. });
  102. });
  103. },
  104. getContainerRect() {
  105. const nodesRef = this.data.container();
  106. return new Promise((resolve) =>
  107. nodesRef.boundingClientRect(resolve).exec()
  108. );
  109. },
  110. },
  111. });