diff --git a/example/pages/tab/index.js b/example/pages/tab/index.js index 9906a9b9..fb653b01 100644 --- a/example/pages/tab/index.js +++ b/example/pages/tab/index.js @@ -25,5 +25,11 @@ Page({ title: `点击标签 ${event.detail.index + 1}`, icon: 'none' }); + }, + + onPageScroll(event) { + this.setData({ + scrollTop: event.scrollTop + }); } }); diff --git a/example/pages/tab/index.wxml b/example/pages/tab/index.wxml index 18891f85..3ef5fe55 100644 --- a/example/pages/tab/index.wxml +++ b/example/pages/tab/index.wxml @@ -87,7 +87,7 @@ - + - + {{ '内容' + item }} diff --git a/packages/tabs/index.ts b/packages/tabs/index.ts index 75c867e3..8c572278 100644 --- a/packages/tabs/index.ts +++ b/packages/tabs/index.ts @@ -67,6 +67,10 @@ VantComponent({ offsetTop: { type: Number, value: 0 + }, + scrollTop: { + type: Number, + value: 0 } }, @@ -91,6 +95,7 @@ VantComponent({ lineHeight: 'setLine', active: 'setActiveTab', animated: 'setTrack', + scrollTop: 'onScroll', offsetTop: 'setWrapStyle' }, @@ -102,8 +107,6 @@ VantComponent({ this.setLine(); this.setTrack(); this.scrollIntoView(); - this.observerTabScroll(); - this.observerContentScroll(); }, destroyed() { @@ -319,55 +322,39 @@ VantComponent({ }); }, - observerTabScroll() { + // adjust tab position + onScroll(scrollTop) { if (!this.data.sticky) return; const { offsetTop } = this.data; - wx.createIntersectionObserver(this, { - thresholds: [1] - }).relativeToViewport().observe('.van-tabs', result => { - const { top } = result.boundingClientRect; - let position = ''; - if (offsetTop > top) { - position = 'top'; - } + this.getRect('.van-tabs').then(rect => { + const { top, height } = rect; - this.$emit('scroll', { - scrollTop: top + offsetTop, - isFixed: position === 'top' + this.getRect('.van-tabs__wrap').then(rect => { + const { height: wrapHeight } = rect; + let position = ''; + + if (offsetTop > top + height - wrapHeight) { + position = 'bottom'; + } else if (offsetTop > top) { + position = 'top'; + } + + this.$emit('scroll', { + scrollTop: scrollTop + offsetTop, + isFixed: position === 'top' + }); + + if (position !== this.data.position) { + this.set({ + position + }, () => { + this.setWrapStyle(); + }); + } }); - - this.setPosition(position); }); - }, - - observerContentScroll() { - if (!this.data.sticky) return; - - const { offsetTop } = this.data; - wx.createIntersectionObserver(this).relativeToViewport().observe('.van-tabs__content', result => { - const { top } = result.boundingClientRect; - let position = ''; - - if (result.intersectionRatio <= 0) { - position = 'bottom'; - } else if (offsetTop > top) { - position = 'top'; - } - - this.setPosition(position); - }); - }, - - setPosition(position) { - if (position !== this.data.position) { - this.set({ - position - }, () => { - this.setWrapStyle(); - }); - } } } });