关于JavaScript中判断滚动条到底部的说明

判断滚动条到底部,需要用到DOM的三个属性值,即scrollTop(滚动条在Y轴上的滚动距离)、clientHeight(内容可视区域的高度)、scrollHeight(容可视区域的高度加上溢出滚动的距离)。从这个三个属性可以看出来,滚动条到底部的条件即为:

scrollTop + clientHeight == scrollHeight

一、使用标准DOM方法:

// 定义滚动条判断方法
(function (window, undefined) {
    if (typeof (window.getScrollTop) != "function") {
        // 获取滚动条在Y轴上的滚动距离  
        window.getScrollTop = function () {
            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;
        };
    }
    if (typeof (window.getScrollHeight) != "function") {
        // 获取文档的总高度 
        window.getScrollHeight = function () {
            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;
        };
    }
    if (typeof (window.getWindowHeight) != "function") {
        // 获取浏览器视口的高度 
        window.getWindowHeight = function () {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        };
    }
})(window);

// 添加滚动事件
window.onscroll = function () {
    // 判断是否滚动条是否在底部
    if (getScrollTop() + getWindowHeight() == getScrollHeight()) {
        alert("滚动条在底部");
    }
};

二、使用jQuery框架方法:

// 定义jQuery对象
var $window = jQuery(window);
var $document = jQuery(document);
// 添加滚动事件
$window.scroll(function () {
    // 获取滚动条在Y轴上的滚动距离
    var scrollTop = $window.scrollTop();
    // 获取文档的总高度 
    var scrollHeight = $document.height();
    // 获取浏览器视口的高度 
    var windowHeight = $window.height();
    // 判断是否滚动条是否在底部
    if (scrollTop + windowHeight == scrollHeight) {
        alert("滚动条在底部");
    }
});

发表评论