Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

上拉加载的简单实现 #16

Open
lazyken opened this issue Aug 22, 2018 · 0 comments
Open

上拉加载的简单实现 #16

lazyken opened this issue Aug 22, 2018 · 0 comments

Comments

@lazyken
Copy link
Owner

lazyken commented Aug 22, 2018

获取滚动条滚动的距离

function getScrollTop() {
  var scrollTop = 0;
  if(document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop;
  } else if(document.body) {
    scrollTop = document.body.scrollTop;
  }
  return scrollTop;
}

根据页面是否声明doctype需要做一下兼容处理,并且不同浏览器也会有一些差异。这里有个参考,文章给出了一个解决方案:

var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;

关于clientHeightoffsetHeightscrollHeightoffsetTopscrollTop不是那么好区分,这里也有一个挺好的参考

获取当前可视范围的高度

function getClientHeight() {
  var clientHeight = 0;
  if(document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
  } else {
    clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
  }
  return clientHeight;
}

获取文档完整的高度

function getScrollHeight() {
  return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}

滚动时触发

window.onscroll = function() {
  if(getScrollTop() + getClientHeight() == getScrollHeight()) {
    //do something
  }
}

由于滚动事件触发的比较频繁,可以利用节流函数来处理一下,参考《javaScript高级程序设计》p615,throttle(n.节流阀;vi.节流,减速)函数

function throttle(method, context) {
  clearTimeout(method.tId);
  method.tId = setTimeout(function() {
    method.call(context);
  }, 100);
}

throttle()函数接受两个参数:要执行的函数以及在哪个作用域中执行。上面这个函数首先清除之前设置的任何定时器。定时器代码使用call()来确保方法在适当的环境中执行。如果没有给出第个参数,那么就会在全局作用域内执行该方法。

function getData() {
  //do something
}
window.onscroll = function() {
  throttle(getData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant