摘要
滑動頁面到底,自動加載數據算是一個很常用的功能,減少用戶操作,增加用戶體驗,讓用戶很順暢的查看數據,但是瀏覽器廠商太多,有些方法和屬性不兼容,得到的值也是大不相同。
問題描述
手機型號紅米note7自帶瀏覽器中,document.documentElement.scrollTop的值是小數,document.body.scrollTop值為0,而在微信瀏覽器中document.body.scrollTop有值并且為整數,document.documentElement.scrollTop值為0,各大瀏覽器對于數據的處理不一樣,導致最后判斷觸底
這個等式不成立,不觸發加載數據的條件,其次應該要做小范圍的容錯處理,在某個范圍內成立就行
解決方案
按照這個公式計算各部分的值
// 節流函數
function throttle(func, wait, mustRun) {
let timeout,
startTime = new Date();
return function() {
let context = this,
args = arguments,
curTime = new Date();
clearTimeout(timeout);
// 如果達到了規定的觸發時間間隔,觸發 handler
if (curTime - startTime >= mustRun) {
func.apply(context, args);
startTime = curTime;
// 沒達到觸發間隔,重新設定定時器
} else {
timeout = setTimeout(func, wait);
}
};
}
// 可滾動高度
let scrollHeight = () =>
document.body.scrollHeight || document.documentElement.scrollHeight;
// 可視窗口高度
let keshiHeight = () =>
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
// 注:小米瀏覽器對于scrollTop的值會有小數,需要做取整操作
// 向上滾動的高度,各大瀏覽器的計算法則不一樣,得到的值可能有小數
let scrollTopHeight = () =>
Math.ceil(document.body.scrollTop || document.documentElement.scrollTop);
window.onscroll = throttle(
() => {
// 增加容錯范圍, 提前觸發加載
if (scrollHeight() - 50 <= keshiHeight() + scrollTopHeight()) {
// 業務邏輯操作,對號入座
if (!this.noMore) {
console.log("bottom");
this.pageNo++;
this.getDataFn();
}
}
},
300,
300
);