HTML頁面滑動到最底部觸發事件


其實基本原理做一個判斷,如果 頁面總高度  =  視口高度  +  瀏覽器窗口上邊界內容高度 ,那么就是把頁面滑動到了最低部,然后執行一個事件。

 

//要觸發的事件(自己定義事件的內容)

  function ajax_function() {
    window.location.href = 'http://baidu.com';
  }

 

  var timeoutInt; // 要保證最后要運行一次

  // window.onscroll窗口添加滾動條事件
  window.onscroll = function () {
    setTimeout(function () {
      if (timeoutInt != undefined) {
        window.clearTimeout(timeoutInt);
      }
      timeoutInt = window.setTimeout(function () {
        //監聽事件內容
        if(getScrollHeight() == getDocumentTop() + getWindowHeight()){
          //當滾動條到底時,這里是觸發內容
          //異步請求數據,局部刷新dom
          ajax_function()//調用上面自定義的事件函數。
        }
      }, 105);
    }, 100);
  }

 

  //(瀏覽器窗口上邊界內容高度)
  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;
    console.log("scrollTop:"+scrollTop);
    return scrollTop;
  }

 

  //可視窗口高度(屏幕可以看見的高度)
  function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
      windowHeight = document.documentElement.clientHeight;
    } else {
      windowHeight = document.body.clientHeight;
    }
    console.log("windowHeight:"+windowHeight);
    return windowHeight;
  }

 

  //滾動條滾動高度(即整個網頁的高度)
  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;
    console.log("scrollHeight:"+scrollHeight);
    return scrollHeight;
  }

 


免責聲明!

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



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