略微加速

略速 - 互联网笔记

js实现监听手机滑动到底部触发事件

2020-12-09 leiting (2362阅读)

标签 JavaScript

首先要清楚3个定义:

  1. 文档高度

    这是整个页面的高度

  2. 可视窗口高度

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

  3. 滚动条滚动高度

    滚动条下滑过的高度

 

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

 

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

//文档高度
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;
}

window.onscroll = function () {
    //监听事件内容
    if(getScrollHeight() == getWindowHeight() + getDocumentTop()){
        //当滚动条到底时,这里是触发内容
        //异步请求数据,局部刷新dom
        $('body').append('<div style="height: 200px;"></div>');
    }
}


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3