欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-14 12:13:57
判断滚动条到底部,需要用到dom的三个属性值,即scrolltop、clientheight、scrollheight。 scrolltop为滚动条在y轴上的滚动距离。 cli...

判断滚动条到底部,需要用到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");
  }
});