上拉加载在h5移动开发经常需要用到,就类似于
有兴趣的同学可以查看react-loadmore,使用起来非常简单!
一般我们的做法是判断scrollTop和clientHeight对比scrollHeight,得出是否在底部。
参考detect-if-browser-window-is-scrolled-to-bottom
let scrollTop =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
let scrollHeight =
(document.documentElement && document.documentElement.scrollHeight) ||
document.body.scrollHeight;
let clientHeight =
document.documentElement.clientHeight || window.innerHeight;
let scrolledToBottom =
Math.ceil(scrollTop + clientHeight) >= scrollHeight;
复制代码
但是这种做法在移动端会有各种各样的问题,包括浏览器版本,ios,Android。
最近发现一种比较简单的办法~
使用 Intersection Observer
此方法非常简单,只需要为元素生成一个IntersectionObserver,并且监听该元素,然后在监听的回调判断元素的intersectionRatio比率即可达到所需。这是核心代码.
componentDidMount() {
if (!this.props.Footer) this._svgaLoad();
try {
const node = document.getElementById('bottom')
this.observer = new IntersectionObserver(this.insideViewportCb);
this.observer.observe(node);
} catch (err) {
console.log("err in finding node", err);
}
window.addEventListener("scroll", this.handleOnScroll);
}
insideViewportCb(entries) {
const { fetching, onBottom } = this.props;
entries.forEach(element => {
//在viewport里面
if (element.intersectionRatio > 0&&!fetching) {
onBottom();
}
});
}
复制代码
给定一个底部的样式,然后用IntersectionObserver对它进行监听,只要判断它在viewportport就可以触发加载!
有兴趣的同学可以查看react-loadmore,使用起来非常简单!