当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 判断滚动条到底部的JS代码

判断滚动条到底部的JS代码

2019年03月23日  | 移动技术网IT编程  | 我要评论

判断滚动条到底部,需要用到dom的三个属性值,即scrolltop、clientheight、scrollheight。

scrolltop为滚动条在y轴上的滚动距离。

clientheight为内容可视区域的高度。

scrollheight为内容可视区域的高度加上溢出(滚动)的距离。

滚动条到底部的条件即为scrolltop + clientheight == scrollheight

//滚动条在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("you are in the bottom!");
  }
};

jquery

$(window).scroll(function(){
  var scrolltop = $(this).scrolltop();
  var scrollheight = $(document).height();
  var windowheight = $(this).height();
  if(scrolltop + windowheight == scrollheight){
    alert("you are in the bottom");
  }
});

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网