Skip to content

Instantly share code, notes, and snippets.

@zhuweiyou
Created August 18, 2023 09:51
Show Gist options
  • Save zhuweiyou/77eeb66d0818e57924d44a986f270a15 to your computer and use it in GitHub Desktop.
Save zhuweiyou/77eeb66d0818e57924d44a986f270a15 to your computer and use it in GitHub Desktop.
监听滚动到底部
export function onReachBottomContainer(container, callback, offset = 50) {
const element = typeof container === 'string' ? document.querySelector(container) : container
function onScroll() {
const scrollHeight = element.scrollHeight
const scrollTop = element.scrollTop
const clientHeight = element.clientHeight
if (scrollHeight - scrollTop <= clientHeight + offset) {
callback()
}
}
element.addEventListener('scroll', onScroll)
return () => element.removeEventListener('scroll', onScroll)
}
export function onReachBottom(callback, offset = 50) {
function onScroll() {
const documentHeight = document.body.scrollHeight
const windowHeight = window.innerHeight
const scrollHeight = window.scrollY
if (scrollHeight + windowHeight >= documentHeight - offset) {
callback()
}
}
window.addEventListener('scroll', onScroll)
return () => window.removeEventListener('scroll', onScroll)
}
import { onReachBottom, onReachBottomContainer } from './on-reach-bottom.js'
// body
onReachBottom(() => {
console.log('on reach bottom')
}, 50)
// container
const off = onReachBottomContainer(
'#parent-element',
() => {
console.log('on reach bottom')
},
50
)
// remove listener
off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment