上拉加載在h5移動開發常常須要用到,就相似於 javascript
有興趣的同窗能夠查看react-loadmore,使用起來很是簡單!java
通常咱們的作法是判斷scrollTop和clientHeight對比scrollHeight,得出是否在底部。node
參考detect-if-browser-window-is-scrolled-to-bottomreact
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。ios
最近發現一種比較簡單的辦法~git
此方法很是簡單,只須要爲元素生成一個IntersectionObserver,而且監聽該元素,而後在監聽的回調判斷元素的intersectionRatio比率便可達到所需。這是核心代碼.github
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,使用起來很是簡單!bash