前端弟中弟,问题都是项目中遇到的,因此记录了下来。javascript
我的博客前端
目前学习Flutter还原豆瓣 ,以此深刻了解Flutter,求大佬们给个Star ❤ ❀java
github.com/jahnli/flut…jquery
原生js实现思路
须要三个高度:scrollHeight(文档内容实际高度,包括超出视窗的溢出部分)、scrollTop(滚动条滚动距离)、clientHeight(窗口可视范围高度)。当 clientHeight + scrollTop >= scrollHeight 时,表示已经抵达内容的底部了,能够加载更多内容。
// Js代码
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()
}
},
// 销毁监听 (坑:移除监听事件时加true不然销毁不成功)
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>
复制代码