我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
当前回答
如上所述,代码可能无法在所有设备和浏览器上运行。下面是经过测试的工作代码,将兼容所有主要设备(iPhone, Android, PC)在所有浏览器(Chrome, IE, Edge, Firefox和Safari)。
window.onscroll = function(ev) { var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); if ((window.innerHeight + window.scrollY) >= pageHeight) { console.log("You are at the bottom of the page."); } }; <html> <body> <div style="width:100%; height:1500px"> <p>Keep scrolling the page till end...</p> </div> </body> </html>
其他回答
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
};
看到演示
公认的答案对我不起作用。这是:
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
// you're at the bottom of the page
console.log("Bottom of page");
}
};
如果您希望支持旧的浏览器(IE9),请使用别名窗口。pageYOffset有更好的支持。
我为移动设备和桌面尝试了这个功能,这对我来说是工作,这里的一些评论在移动/Android设备上不起作用,顺便说一句,谢谢你的问题。程序员们,坚持下去吧!
window.addEventListener("scroll", function(el) {
const scrollY = window.scrollY + window.innerHeight + 2;
const bodyScroll = document.body.offsetHeight;
console.log("Scroll Y : " + scrollY);
console.log("Body : " + bodyScroll);
if(scrollY >= bodyScroll){
alert("Bottom Page");
}
})
window.onscroll = function(ev) {
if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
alert("you're at the bottom of the page");
}
};
这个答案将修复边缘情况,这是因为pageYOffset是double,而innerHeight和offsetHeight是长,所以当浏览器给你的信息,你可能是一个像素短。 例如:在这一页的底部
真正的窗口。innerHeight = 10.2
真正的窗口。pageYOffset = 5.4
true document.body.offsetHeight = 15.6
我们的计算结果是: 10 + 5.4 >= 16,是错误的
要解决这个问题,我们可以用数学。pageYOffset值上的ceil。
希望这能有所帮助。
这是
window.onscroll = function() {
// @var int totalPageHeight
var totalPageHeight = document.body.scrollHeight;
// @var int scrollPoint
var scrollPoint = window.scrollY + window.innerHeight;
// check if we hit the bottom of the page
if(scrollPoint >= totalPageHeight)
{
console.log("at the bottom");
}
}
如果您正在寻找支持旧浏览器(IE9)的替换窗口。使用window.pageYOffset进行滚动