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

来源:互联网 发布:石田电子称软件 编辑:程序博客网 时间:2024/06/09 19:57

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

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

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

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

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


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



//根据某个节点来操作

var _h=0,_st=0,_sh=0;

_st=$(this)[0].scrollTop;_sh=$(this)[0].scrollHeight;if(h+_st>=_sh){    console.log("buttom");}

由于zeptojs对scrolltop错在一些问,可以通过javascript实现

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 排卵期逼为啥老是出水 女子排卵期是什么时候 正常排卵期是什么时候 排卵期下腹隐隐作痛 排卵期会有很多白带吗 排卵期身体有什么反应 过了排卵期会怀孕吗 排卵期有什么症状腰痛 排卵期计算法周期表 女人的排卵期怎么算 排卵期排出褐色分泌物 女生排卵期有什么反应 排卵期出血的症状和图片 排卵期症状有哪些症状 排卵期是不是容易怀孕 一个月排卵期有几天 排卵期肚子痛怎么回事 排卵期体温会升高吗 排卵期测体温怎么测 排卵期肚子疼是在排卵吗 排卵期腰痛是怎么回事 排卵期没有射会怀孕吗 女人排卵期计算方法 排卵期有什么症状白带 排卵期是什么时候有什么反应 女孩排卵期是什么时候 排卵期不带套子外射会怀孕吗 排卵期怎么算计算器 女的排卵期是什么时候 女生排卵期有什么特征 排卵期一定会怀孕吗 排卵期小肚子疼是怎么回事 排卵期身体有什么症状 女人的排卵期怎么算才准确 女性排卵期有什么症状 什么是排卵期怎么计算 排卵期第几天容易怀孕 排卵期是什么时候到什么时候 排卵期有什么症状或感觉 排卵期体重会增加吗 排卵期受完孕有什么感觉