Created
August 18, 2023 09:51
-
-
Save zhuweiyou/77eeb66d0818e57924d44a986f270a15 to your computer and use it in GitHub Desktop.
监听滚动到底部
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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