jQuery判断页面滚动到底部

有时候我们需要页面滚动到底部的时候去加载更多的数据,实现思路基本上就是判断浏览器页面是否滚动到了页面底部,当滚动到页面底部的时候,用AJAX异步获取数据然后加载到页面中。

利用jQuery判断浏览器页面是否滑动到了底部:

基础:

<script type="text/javascript">
    // scroll event
    $(window).scroll(function(){
        // scroll at bottom
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            // load data
        }
    });
</script>

$(window).scroll():方法用于监听滚动条的滚动
$(window).scrollTop() :用于计算窗口相对于滚动条顶部的偏移, $(window).height()$(document).height() 分别表示当面窗口的高度和文档的高度。
注意:在页面前面加上<!DOCTYPE html>要不然谷歌浏览器$(window).height()==$(document).height()

进阶:

这里设置isBottom的原因是为了防止滚动到底部多次触发事件问题

var lastIndex=0;
 var isBottom=true;//触发开关,防止多次调用事件 
    $(window).scroll(function(){
     if (e.currentTarget.scrollTop >= lastIndex) {//只有向下滑动的时候才执行.0d`sd1lastIndex = e.currentTarget.scrollTop;
        // scroll at bottom
       //当内容滚动到底部时加载新的内容 10当距离最底部10个像素时开始加载.  
          if ($(window).scrollTop() + $(window).height() +10>= $(document).height()) {
            // load data
            if(isBottom){
              isBottom=false;

              console.log(isBottom);
              setTimeout(function(){
                isBottom=true;
               
              },5000);
            }
}
        }
    });

猜你喜欢

转载自blog.csdn.net/weixin_34354173/article/details/86924946