检测滚动是否触及页面底部

Detect if scroll has touched bottom of page

本文关键字:底部 滚动 是否 检测      更新时间:2023-09-26

这是我用来检测用户是否通过滚动到达页面底部的代码。

它在Chrome,Safari和Firefox中工作正常,但是在IE8中,当滚动到达页面底部时,showNextItems函数被调用两次。谁能确定为什么,以及如何解决它?

        $(window).scroll(function() {            
            if($(window).scrollTop() + $(window).height() == getDocHeight()) {
                if ($('#digitalContent p:hidden').size() > 0) {
                    getAjaxLoader($('.loader'), false);
                    getAjaxLoader($('.loader'), true);
                    window.setTimeout(function() {                      
                          getAjaxLoader($('.loader'), false);    
                              showNextItems('');
                    }, 1500);
                }
            }
        });

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

你可以做:

function isBottom(m, wh) {
    if (m === "init") {
        if (wh === "off") $(window).off("scroll.isBottom");
        else if (wh === "on") {
            $(window).on("scroll.isBottom", function () {
                console.log(isBottom("scroll"));
            });
        }
    } else if (m === "scroll") {
        var isIt = $(document).height() - ($(window).scrollTop() + $(window).height()) <= 0;
        isBottom("init", "off");
        setTimeout(function () {
            isBottom("init", "on");
        }, 100);
        return isIt;
    }
}
$(document).ready(function () {
    isBottom("init", "on");
});

演示:

只有在页面底部时才应在IE8中登录true

function isBottom(m, wh) {
	if (m === "init") {
		if (wh === "off") $(window).off("scroll.isBottom");
		else if (wh === "on") {
			$(window).on("scroll.isBottom", function () {
				console.log(isBottom("scroll"));
			});
		}
	} else if (m === "scroll") {
		var isIt = $(document).height() - ($(window).scrollTop() + $(window).height()) <= 0;
		isBottom("init", "off");
		setTimeout(function () {
			isBottom("init", "on");
		}, 100);
		return isIt;
	}
}
$(document).ready(function () {
	isBottom("init", "on");
});
div {
  height: 2000px;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>