您的位置:首页 > 资讯

网站JS滚动刷新技术原理分析

日期:2024-09-15 00:38    点击:39

我们在网页制作中, 经常会遇到滚动刷新, 比如我们经常使用的分页, 当滚动条到底后, 我们就会请求下一页的数据, 然后刷新页面.那么我们如何实现这个功能呢?


首先要清楚 3 个定义:

  • 文档高度: 这是整个页面的高度
  • 可视窗口高度: 这是你看到的浏览器可视屏幕高度
  • 滚动条滚动高度: 这是滚动条下滑过的高度

所以, 当 文档高度 = 可视窗口高度 + 滚动条高度 时,滚动条正好到底.

那我们就来定义三个不同的方法,分别获取上面 3 个高度值
//文档高度
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;
}

//可视窗口高度
function getWindowHeight() {
  var windowHeight = 0;
  if (document.compatMode == "CSS1Compat") {
    windowHeight = document.documentElement.clientHeight;
  } else {
    windowHeight = document.body.clientHeight;
  }
  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;
  return scrollHeight;
}


下面我们需要一个监听滚动条的事件;

window.onscroll = function () {
  //监听事件内容
};

当滚动条移动马上就出发我们上面定义的事件触发函数,
  但是我们要求的是滚动条到底后才触发,
  (所以自然这个触发事件里面需要逻辑控制一下.window.onscroll = function () {
    //监听事件内容
    if (getScrollHeight() == getWindowHeight() + getDocumentTop()) {
      //当滚动条到底时,这里是触发内容
      //异步请求数据,局部刷新dom
      ajax_function();
    }
  });
至此我们已能通过JS判断页面滚动加载数据
售前客服
咨询电话
点击查看联系方式