需求說明:當(dāng)用戶瀏覽到頁面底部時(shí)候,自動(dòng)加載下一頁的內(nèi)容
實(shí)現(xiàn)原理:JS獲取當(dāng)前滾動(dòng)條高度、滾動(dòng)條長(zhǎng)度以及頁面總長(zhǎng)度,當(dāng)滾動(dòng)條高度加上當(dāng)前滾動(dòng)條長(zhǎng)度等于頁面總長(zhǎng)度的時(shí)候,頁面到達(dá)底部,此時(shí)可以觸發(fā)ajax加載下一頁內(nèi)容。代碼如下
<script>
//獲取滾動(dòng)條當(dāng)前的位置
function getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
}
else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
//獲取當(dāng)前可視范圍的高度
function getClientHeight() {
var clientHeight = 0;
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
}
else {
clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
}
return clientHeight;
}
//獲取文檔完整的高度
function getScrollHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
window.onscroll = function () {
if (getScrollTop() + getClientHeight() == getScrollHeight()) {
//ajax從這里開始
</script>