diff --git a/packages/taro-router/src/scroll.ts b/packages/taro-router/src/scroll.ts index 504b9f06bf07..629bea2f5003 100644 --- a/packages/taro-router/src/scroll.ts +++ b/packages/taro-router/src/scroll.ts @@ -2,16 +2,18 @@ import type { PageInstance } from '@tarojs/runtime' import { PageConfig } from '@tarojs/taro' let pageScrollFn +let pageDOM: Element | Window = window export function bindPageScroll (page: PageInstance, config: Partial) { - window.removeEventListener('scroll', pageScrollFn) + pageDOM.removeEventListener('scroll', pageScrollFn) + pageDOM = getScrollContainer() const distance = config.onReachBottomDistance || 50 let isReachBottom = false pageScrollFn = function () { page.onPageScroll && page.onPageScroll({ - scrollTop: window.scrollY + scrollTop: pageDOM instanceof Window ? window.scrollY : pageDOM.scrollTop }) if (isReachBottom && getOffset() > distance) { @@ -28,9 +30,34 @@ export function bindPageScroll (page: PageInstance, config: Partial) } } - window.addEventListener('scroll', pageScrollFn, false) + pageDOM.addEventListener('scroll', pageScrollFn, false) +} + +window.addEventListener('DOMSubtreeModified', (e) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-ignore + // @ts-ignore + const className = e.target?.className + if (className && /taro-tabbar__/.test(className)) { + pageDOM.removeEventListener('scroll', pageScrollFn) + pageDOM = getScrollContainer() + pageDOM.addEventListener('scroll', pageScrollFn, false) + } +}, false) + +function getScrollContainer (): Element | Window { + if (document.querySelector('.taro-tabbar__tabbar') === null) { + // 没设置tabbar + return window + } else { + // 有设置tabbar + return document.querySelector('.taro-tabbar__panel') || window + } } function getOffset () { - return document.documentElement.scrollHeight - window.scrollY - window.innerHeight + if (pageDOM instanceof Window) { + return document.documentElement.scrollHeight - window.scrollY - window.innerHeight + } else { + return pageDOM.scrollHeight - pageDOM.scrollTop - pageDOM.clientHeight + } }