美文网首页
2020-03-06

2020-03-06

作者: 明小猪 | 来源:发表于2020-03-06 11:59 被阅读0次

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

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

    step1:获取滑动高度

     //滑动高度
    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

          本文链接:https://www.haomeiwen.com/subject/yjbvrhtx.html