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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM