2020-03-06

嘻嘻嘻 我又回来了
总结下有关js滑动到底部加载数据问题,先记录一个方法。
代码部分摘自 https://blog.csdn.net/mouday/article/details/82760467

文章总长度 = 滑动长度 + 可视窗口高度

step1:获取滑动高度

  • 关于document.documentElement和document.body的区别 见我另一篇博文吧https://www.jianshu.com/p/b63090427164
 //滑动高度
function getDocumentTop() {
    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;
}

step2:可视窗口高度

//可视窗口高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

step3:获取文档高度

//文档高度
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;
}

step4:判断是否滑动到底部,异步加载数据

window.onscroll = function () {
    //监听事件内容
    if (getScrollHeight() == getWindowHeight() + getDocumentTop()) {
        //当滚动条到底时,这里是触发内容
        //异步请求数据,局部刷新dom
        ajax_function(); 
    }
}

你可能感兴趣的:(2020-03-06)