Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(h5): scroll-page event #8522

Merged
merged 3 commits into from
Jan 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions packages/taro-router/src/scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PageConfig>) {
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) {
Expand All @@ -28,9 +30,34 @@ export function bindPageScroll (page: PageInstance, config: Partial<PageConfig>)
}
}

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
}
}