我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
当前回答
令人惊讶的是,没有一个解决方案对我有效。我认为这是因为我的css是混乱的,和身体没有围绕所有的内容使用高度:100%(不知道为什么)。然而,在寻找解决方案时,我想到了一些东西……基本上是一样的,但也许值得一看——我是编程新手,所以抱歉,如果它做同样的事情更慢,支持更少或类似的事情……
window.onscroll = function(evt) {
var check = (Element.getBoundingClientRect().bottom - window.innerHeight) <= 0;
if (check) { console.log("You're at the bottom!"); }
};
其他回答
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(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
// you're at the bottom of the page
console.log("Bottom of page");
}
};
如果您希望支持旧的浏览器(IE9),请使用别名窗口。pageYOffset有更好的支持。
新的解决方案。
一个问题是缺少标准的主滚动元素。最近实施的文件。scrollingElement可以用来尝试克服这个问题。下面是一个跨浏览器的解决方案。
function atEnd() {
var c = [document.scrollingElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight].sort(function(a,b){return b-a}) // select longest candidate for scrollable length
return (window.innerHeight + window.scrollY + 2 >= c[0]) // compare with scroll position + some give
}
function scrolling() {
if (atEnd())
//do something
}
window.addEventListener('scroll', scrolling, {passive: true});
我只是在我的页面底部放置了一个小图像,加载="lazy",这样当用户向下滚动时,浏览器才会加载它。然后图像触发一个php计数器脚本,返回一个真实的图像
<img loading="lazy" src="zaehler_seitenende.php?rand=<?=rand(1,1000);?>">
<?php
@header("Location: https://domain.de/4trpx.gif");
如果你喜欢jquery
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// doSomethingHere();
}
});