当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现判断滚动条滚动到document底部的方法分析

jQuery实现判断滚动条滚动到document底部的方法分析

2019年09月06日  | 移动技术网IT编程  | 我要评论
本文实例讲述了jquery实现判断滚动条滚动到document底部的方法。分享给大家供大家参考,具体如下: 滚动条没有实际的高度。只是为了呈现效果才在外型上面有长度。

本文实例讲述了jquery实现判断滚动条滚动到document底部的方法。分享给大家供大家参考,具体如下:

滚动条没有实际的高度。只是为了呈现效果才在外型上面有长度。

在js当中也没有提供滚动条的高度api。

参考了网上有关资料:判断滚动条到底部的基本逻辑是滚动条滚动的高度加上视口的高度,正好是document的高度,公式表示为

滚动条滚动的高度+浏览器视口的高度>=document的高度。

参考网上资料,具体代码如下:

//滚动条在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;
    windowheight = document.documentelement.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");
  }
});

代码测试有效果。

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网