移動端加載數(shù)據(jù)時抖僵,由于數(shù)據(jù)太多,不會一次性全部加載出來裆针。有些會采用pc端那樣用分頁碼的形式寺晌,但是更多的確實滑動滾動條到內(nèi)容最后呻征,加載更多內(nèi)容出來。一般引入了三方的前端框架和插件陆赋,基本都會有此功能嚷闭。偶爾會需要采用原生js實現(xiàn),故而此處就介紹下原生js的實現(xiàn)方式胞锰。另外附上jquery的實現(xiàn)方式。
原生js實現(xiàn)思路
需要三個高度:
scrollHeight(文檔內(nèi)容實際高度顺饮,包括超出視窗的溢出部分)、
scrollTop(滾動條滾動距離)兼雄、
clientHeight(窗口可視范圍高度)帽蝶。
當 clientHeight + scrollTop >= scrollHeight
時,表示已經(jīng)抵達內(nèi)容的底部了励稳,可以加載更多內(nèi)容。
- scrollHeight:可以通過
document.documentElement.scrollHeight
驹尼、document.body.scrollHeight
獲取; - clientHeight:可以通過
window.innerHeight
、document.documentElement.clientHeight
獲取; - scrollTop:可以通過
window.pageYOffset
、document.documentElement.scrollTop
獲取;
下面附上三者之間的關系:
image.png
測試代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>scroll</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<style>
* {
margin: 0;
padding: 0;
}
.scroll{
margin-top: 0px;
border: 2px solid #00f;
height: 2000px;
}
#js_con {
position: fixed;
top: 50px;
}
</style>
</head>
<body>
<div class="scroll">
<div id="js_con"></div>
</div>
</body>
<script>
window.onscroll = function() {
var str = ``;
str += `scrollHeight:(${document.documentElement.scrollHeight}, ${document.body.scrollHeight})<br />`;
str += `clientHeight/innerHeight:(${document.documentElement.clientHeight}, ${window.innerHeight})<br />`;
str += `scrollTop/pageYOffset:(${document.documentElement.scrollTop}, ${window.pageYOffset})`;
document.getElementById('js_con').innerHTML = str;
console.log(str);
}
</script>
</html>
jquery實現(xiàn)方式:
<script>
$(window).on("resize scroll",function() {
var windowHeight = $(window).height();//當前窗口的高度
var scrollTop = $(window).scrollTop();//當前滾動條從上往下滾動的距離
var docHeight = $(document).height(); //當前文檔的高度
console.log(scrollTop, windowHeight, docHeight);
// 觸底公式:(滾動條滾動的高度 + 可視窗口的高度 = 文檔的高度) 這個是基本的公式
if (scrollTop + windowHeight >= docHeight) {
console.log("===加載更多數(shù)據(jù)===");
}
});
</script>
JQuery 獲取三個高度 和 原生獲取三個高度的方式:
$(document).height(); == document.documentElement.scrollHeight; // 文檔內(nèi)容的實際高度
$(window).scrollTop(); == document.documentElement.scrollTop; // 滾動條滾動高度
$(window).height(); == document.documentElement.clientHeight; // 可視窗口高度