其他分享
首页 > 其他分享> > 用js去动态监测用户是否滑动到页面底部

用js去动态监测用户是否滑动到页面底部

作者:互联网

用js去动态监测用户是否滑动到页面底部

vue写法


//滚动条在Y轴上的滚动距离
 
function getScrollTop(){
  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 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;
}
 
//浏览器视口的高度
 
function getWindowHeight(){
  var windowHeight = 0;
  if(document.compatMode == "CSS1Compat"){
    windowHeight = document.documentElement.clientHeight;
  }else{
    windowHeight = document.body.clientHeight;
  }
  return windowHeight;
}
 
window.onscroll = function(){
  if(getScrollTop() + getWindowHeight() == getScrollHeight()){
    alert("已经到最底部了!!");  --这里要注意如果是要执行事件的话最好考虑到你的this的指向问题 不然容易找不到你的事件
  }
};

此写法适用于移动端的上拉加载下一页,相对于插件而言,这种写法方便很多 插件毕竟是插件会有隐形的bug!!!

标签:body,documentScrollTop,documentElement,js,scrollTop,滑动,document,scrollHeight,页面
来源: https://blog.csdn.net/qq_41568769/article/details/114637690