我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
我需要检测用户是否滚动到页面底部。如果它们在页面的底部,当我在底部添加新内容时,我会自动将它们滚动到新的底部。如果他们不在底部,他们正在阅读页面上更高的先前内容,所以我不想自动滚动他们,因为他们想呆在那里。
我如何检测用户是否滚动到页面的底部,或者他们是否在页面上滚动得更高?
当前回答
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
};
看到演示
其他回答
您可以检查窗口的高度和滚动顶部的组合结果是否大于主体的结果
如果窗口。innerHeight +窗口。scroll> = document.body.scrollHeight) {}
const handleScroll = () => {
if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
onScroll();
}
};
这段代码在Firefox和IE中也适用。
如果你用其他方法都不走运,试试这个方法。
窗口。Onscroll = function() { const difference = document.documentElement.scrollHeight - window.innerHeight; const scrollposition = document.documentElement.scrollTop; If (difference - scrollposition <= 2) { alert(“页底!”); } }
如上所述,代码可能无法在所有设备和浏览器上运行。下面是经过测试的工作代码,将兼容所有主要设备(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>
使用defaultView和documentElement嵌入功能代码片段:
const {defaultView} =文档; const {documentElement} =文档; const handler = evt => (() => { const hitBottom = (() => (defaultView.)innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)(); hitBottom ? console.log(“是的”) : console.log(“不”) }); 文档。addEventListener(“滚动”,处理程序); <pre style="height:110vh;background-color:fuchsia">向下滚动</pre>