判断滚动条到底部

判断滚动条到底部,须要用到DOM的三个属性值,即scrollTop、clientHeight、scrollHeight。jquery

scrollTop为滚动条在Y轴上的滚动距离。浏览器

clientHeight为内容可视区域的高度。this

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

从这个三个属性的介绍就能够看出来,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。文档

废话很少少说,赶忙上代码(兼容不一样的浏览器)。get

 

//滚动条在Y轴上的滚动距离io

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

//文档的总高度cli

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;
}scroll

//浏览器视口的高度

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");
  }
});

若是要判断在某一个元素中的滚动条是否到底部,根据相似的思想,将document.body换成特定的元素便可,获取scrollTop和scrollHeight的方式是同样的,可是获取元素可见高度须要用到offsetHeight属性,直接依葫芦画瓢便可。

相关文章
相关标签/搜索