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

在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>

10-07 16:07