js实现页面滑动到最底部触发内容加载

举报
彭世瑜 发表于 2021/08/14 01:43:15 2021/08/14
2.3k+ 0 0
【摘要】 首先要清楚3个定义: 文档高度: 这是整个页面的高度可视窗口高度: 这是你看到的浏览器可视屏幕高度滚动条滚动高度: 滚动条下滑过的高度 所以, 当 文档高度 == 可视窗口高度 + 滚动条高度 时,滚动条正好到底. 以下三个方法分别获取上面3个高度值 scroll-event.js //文档高度 function getDocumentTop() { var ...

首先要清楚3个定义:

  1. 文档高度: 这是整个页面的高度
  2. 可视窗口高度: 这是你看到的浏览器可视屏幕高度
  3. 滚动条滚动高度: 滚动条下滑过的高度

所以, 当 文档高度 == 可视窗口高度 + 滚动条高度 时,滚动条正好到底.

以下三个方法分别获取上面3个高度值

scroll-event.js

//文档高度
function getDocumentTop() { 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 getWindowHeight() { var windowHeight = 0; if (document.compatMode == "CSS1Compat") { windowHeight = document.documentElement.clientHeight; } else { windowHeight = document.body.clientHeight; } return windowHeight;
}

//滚动条滚动高度
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;
}
/*
当滚动条滑动,触发事件,判断是否到达最底部
然后调用ajax处理函数异步加载数据
*/
window.onscroll = function () { //监听事件内容 if (getScrollHeight() == getWindowHeight() + getDocumentTop()) { //当滚动条到底时,这里是触发内容 //异步请求数据,局部刷新dom ajax_function(); }
}
   1
   2
   3
   4
   5
   6
   7
   8
   9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
  
  
 

自己实现的异步加载数据函数模板示例

function ajax_function() { $.get( url, data, function (data) { // dosomething } );
}
   1
   2
   3
   4
   5
   6
   7
   8
   9
  
  
 

关于ajax请求可以参考我的文章: js:jquery的ajax请求模板

参考
js实现移动HTML5页面滑动到最底部触发内容加载

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/82760467

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。