原生js实现思路
需要三个高度:scrollHeight(文档内容实际高度,包括超出视窗的溢出部分)、scrollTop(滚动条滚动距离)、clientHeight(窗口可视范围高度)。当 clientHeight + scrollTop >= scrollHeight 时,表示已经抵达内容的底部了,可以加载更多内容。
window.onscroll= function(){
var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var clientHeight = window.innerHeight || Math.min(document.documentElement.clientHeight,document.body.clientHeight);
if(clientHeight + scrollTop >= scrollHeight){
console.log("===加载更多内容……===");
}
}
Vue的实现方式
mounted() {
window.addEventListener('scroll',this.handleScroll,true)
},
handleScroll(e){
let dom = document.querySelector('.main_content')
let scrollHeight = Math.max(dom.scrollHeight, dom.scrollHeight);
let scrollTop = e.target.scrollTop;
let clientHeight = dom.innerHeight || Math.min(dom.clientHeight,dom.clientHeight);
if(clientHeight + scrollTop >= scrollHeight){
if(this.pageSize > this.total ) return;
this.pageSize += 10
this._getArchives()
}
},
beforeDestroy(){
window.removeEventListener("scroll",this.handleScroll,true)
}
jquery的实现方式
<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("===加载更多数据===");
}
});
</script>