您的位置:首页 > Web前端 > JavaScript

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

2016-11-08 10:56 721 查看
首先要清楚3个定义:

文档高度
这是整个页面的高度

可视窗口高度
这是你看到的浏览器可视屏幕高度

滚动条滚动高度
滚动条下滑过的高度

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

那我们就来定义三个不同的方法,分别获取上面3个高度值

01
//文档高度
02
function
getDocumentTop() {
03
var
scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
04
if
(document.body) {
05
bodyScrollTop = document.body.scrollTop;
06
}
07
if
(document.documentElement) {
08
documentScrollTop = document.documentElement.scrollTop;
09
}
10
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return
scrollTop;
11
}
12
13
//可视窗口高度
14
function
getWindowHeight() {
15
var
windowHeight = 0;
if
(document.compatMode ==
"CSS1Compat"
) {
16
windowHeight = document.documentElement.clientHeight;
17
}
else
{
18
windowHeight = document.body.clientHeight;
19
}
20
return
windowHeight;
21
}
22
23
//滚动条滚动高度
24
function
getScrollHeight() {
25
var
scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
26
if
(document.body) {
27
bodyScrollHeight = document.body.scrollHeight;
28
}
29
if
(document.documentElement) {
30
documentScrollHeight = document.documentElement.scrollHeight;
31
}
32
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return
scrollHeight;
33
}
下面我们需要一个监听滚动条的事件

1
window.onscroll =
function
() {
//监听事件内容}
当滚动条移动马上就出发我们上面定义的事件触发函数,但是我们要求的是滚动条到底后才触发,所以自然这个触发事件里面需要逻辑控制一下.

view
source

print?

1
window.onscroll =
function
() {
2
//监听事件内容
3
if
(getScrollHeight() == getWindowHeight() + getDocumentTop()){
4
//当滚动条到底时,这里是触发内容
5
//异步请求数据,局部刷新dom
6
ajax_function()
7
}
8
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: