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

标签 javascript jquery

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

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

关于javascript - 检测滚动条是否触及页面底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621382/

相关文章:

javascript - 为什么 sort 是 jQuery UI .sortable() 的唯一事件触发?

javascript - JSPM - jspm 安装给出错误 "Registry not found"

javascript - 如何在select2框的最后添加新选项?

javascript - 将 JavaScript Spinner 值从表中提取到电子邮件中

javascript - 带有 jQ​​uery 对话框的 qTip

javascript - Firebase - Vue 数据库集成不起作用

javascript - 需要帮助理解为什么代码中出现这一行

PHP 无法从 Javascript Jquery 获取信息

javascript - 循环遍历分割数组并使用wrapInner输出

javascript - 如果屏幕分辨率小于更改 div 内容?