如何通过 JavaScript 检测指定元素的滚动结束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5527296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect scroll end of the specified element by JavaScript?
提问by Japboy
I'm using Google Chrome 10 and writing JavaScript to detect scroll end.
我正在使用 Google Chrome 10 并编写 JavaScript 来检测滚动结束。
To detect scroll end of window
, the code below worked fine:
要检测 的滚动结束window
,下面的代码工作正常:
window.addEventListener(
'scroll',
function()
{
var scrollTop = document.documentElement.scrollTop ||
document.body.scrollTop;
var offerHeight = document.body.offsetHeight;
var clientHeight = document.documentElement.clientHeight;
if (offsetHeight <= scrollTop + clientHeight)
{
// Scroll end detected
}
},
false
);
Now I want to detect scroll end of the specified element, like <section id="box" style="height: 500px; overflow: auto;">
This is the code that doesn't detect correctly:
现在我想检测指定元素的滚动结束,比如<section id="box" style="height: 500px; overflow: auto;">
这是没有正确检测的代码:
document.getElementById('box').addEventListener(
'scroll',
function()
{
var scrollTop = document.getElementById('box').scrollTop;
var offerHeight = document.getElementById('box').offsetHeight;
var clientHeight = document.getElementById('box').clientHeight;
if (offsetHeight <= scrollTop + clientHeight)
{
// This is called before scroll end!
}
},
false
);
Could someone please fix my code? Thanks.
有人可以修复我的代码吗?谢谢。
采纳答案by Japboy
Fixed.
固定的。
document.getElementById('box').addEventListener(
'scroll',
function()
{
var scrollTop = document.getElementById('box').scrollTop;
var scrollHeight = document.getElementById('box').scrollHeight; // added
var offsetHeight = document.getElementById('box').offsetHeight;
// var clientHeight = document.getElementById('box').clientHeight;
var contentHeight = scrollHeight - offsetHeight; // added
if (contentHeight <= scrollTop) // modified
{
// Now this is called when scroll end!
}
},
false
)