Js实现滚动加载原理(监听滚动条滚动)

原理:就是监听页面滚动事件,分析clientHeight、scrollTop、scrollHeight三者的属性关系。

1.document.compatMode === "CSS1Compat"模式下 ---也就是声明了DTD情况下

window.addEventListener('scroll', function() {
  const clientHeight = document.documentElement.clientHeight;
  const scrollTop = document.documentElement.scrollTop;
  const scrollHeight = document.documentElement.scrollHeight;
  if (clientHeight + scrollTop >= scrollHeight) {
    // 检测到滚动至页面底部,进行后续操作
    // ...
  }
}, false);

 2.document.compatMode监听(完整版)

window.onscroll  = function (){
    var marginBot = 0;
    if (document.compatMode === "CSS1Compat"){
        marginBot = document.documentElement.scrollHeight - (document.documentElement.scrollTop+document.body.scrollTop)-  document.documentElement.clientHeight;
    } else {
        marginBot = document.body.scrollHeight - document.body.scrollTop-  document.body.clientHeight;
    }
    if(marginBot<=0) {
        //do something
    }
}

  以上就是监听浏览器滚动条方式,需注意文档是否声明DTD

原文地址:https://www.cnblogs.com/yxkNotes/p/13950113.html