2020-03-06

嘻嘻嘻 我又回来了
总结下有关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(); 
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 常见前端面试题---其他篇 1、如何理解MVVM模式和MVC模式 MVC是经典的开发模式,model数据库,提供数...
    暮长亭晚阅读 1,189评论 0 0
  • “灵气复苏,就是今天吧…” 木村和树坐在教室的位置上望向窗外,夏季的气息带着灼热,将空气扭曲,太阳的精力在这一年最...
    2a22b79846fa阅读 3,414评论 0 0
  • 专题一 建筑构造与结构要求 2A311010建筑构造要求≦ ≧ 一、建筑物分为“农民工”,分别是农业建筑、民...
    功能美阅读 2,523评论 0 0
  • 花了8天时间看了《人人都是产品经理》《结网》《启示录》《用户体验要素》4本书,这几本书让我对“产品经理”有了更深的...
    RainaL阅读 2,806评论 0 0
  • 如果你的生活搭配总觉得缺少点什么 那么你一定缺一款百搭的人本休闲鞋 人本休闲鞋,新品限时¥48起 二爷同款人本休闲...
    晴好May阅读 1,365评论 0 0