zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JS 实现 页面 加载 内容 滑动 触发 底部
2023-09-14 09:07:18 时间

首先要清楚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(); 
    }
}

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

function ajax_function() {
    $.get(
        url,
        data,
        function (data) {
            // dosomething
        }
    );
}

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

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