在网页中,我们会遇到很多在滚动条到底部的时候有数据正在加载的事件,那么怎样用vue去实现这样的内容呢?本篇只给出一个雏形,结合vue的生命周期用纯javascript写的一个监听函数,后续操作数据库的部分暂且不议。
1、怎样用纯js判断滚动条是否到底部?
先了解几个关键词:
(1)滚动条到顶部的位置:scrollTop
(2)当前窗口内容可视区:windowHeight
(3)滚动条内容的总高度:scrollHeight
触发监听的函数是:
window.onscroll = function(){...}
判断到底部的等式: scrollTop+windowHeight=scrollHeight;
2、主要函数代码
created(){
window.onscroll = function(){
//变量scrollTop是滚动条滚动时,距离顶部的距离
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
//变量windowHeight是可视区的高度
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
//变量scrollHeight是滚动条的总高度
var scrollHeight = document.documentElement.scrollHeight||document.body.scrollHeight;
//滚动条到底部的条件
if(scrollTop+windowHeight==scrollHeight){
//写后台加载数据的函数
console.log("距顶部"+scrollTop+"可视区高度"+windowHeight+"滚动条总高度"+scrollHeight);
}
}
}
下面是另一兼容写法
removeOnscroll() {
//移除滚动监听
window.onscroll=null
},
menu() {
//滚动条在Y轴上的滚动距离
function getScrollTop() {
var scrollTop = 0,
bodyScrollTop = 0,
documentScrollTop = 0;
if (document.body) {
bodyScrollTop = document.body.scrollTop;
}
if (document.documentElement) {
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//文档的总高度
function getScrollHeight() {
var scrollHeight = 0,
bodyScrollHeight = 0,
documentScrollHeight = 0;
if (document.body) {
bodyScrollHeight = document.body.scrollHeight;
}
if (document.documentElement) {
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight :
documentScrollHeight;
return scrollHeight;
}
//浏览器视口的高度
function getWindowHeight() {
var windowHeight = 0;
if (document.compatMode == "CSS1Compat") {
windowHeight = document.documentElement.clientHeight;
} else {
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = ()=> {
if (getScrollTop() + getWindowHeight() == getScrollHeight()) {
console.log('到底了加载更多')
}
};