原生JS实现下拉加载

tips:实现的原理是通过获取①获取滚动条当前的位置②获取当前可视范围的高度 ③获取文档完整的高度

(一)获取滚动条当前的位置
//获取滚动条当前的位置
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;
}
(二)获取当前可视范围的高度
//获取当前可视范围的高度  
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;
}

tips:Math.min是两个值取最小的值,Math.max则相反。

(三)获取文档完整的高度
//获取文档完整的高度 
function getScrollHeight() {
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
(四)实现下拉刷新
//滚动事件触发
window.onscroll = function() {
    if(getScrollTop() + getClientHeight() == getScrollHeight()) {
        console.log('下拉刷新了')
        //此处发起AJAX请求
    }
}

tips:如果想距离底部50px就执行刷新,请将if条件改为getScrollTop() + getClientHeight()+50> getScrollHeight()即可实现。

(五)获取页面元素的位置
var wrapTop =document.getElementById('scrollWrap')
console.log(wrapTop.scrollTop + " " + "滚动条当前的位置")
console.log(wrapTop.scrollHeight + " " + "获取滚动条的高度")

tips:对应的上下左右以及宽高修改一下属性即可,就不一一罗列了。

猜你喜欢

转载自blog.csdn.net/qq_38209578/article/details/79163103