javascript 如何检查滚动条是否在底部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8480466/
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 to check if scrollbar is at the bottom
提问by redoc01
How can you check if the scroll bar is positioned at the bottom? Using JQuery or JavaScript
如何检查滚动条是否位于底部?使用 JQuery 或 JavaScript
回答by Feisty Mango
You find the height of the scrolling container, then compare that to the scroll position. If they are the same, then you have reached the bottom.
您找到滚动容器的高度,然后将其与滚动位置进行比较。如果它们相同,那么您已经到达底部。
<div style="overflow: auto; height: 500px">
</div>
$(document).ready(function()
{
$('div').scroll(function()
{
var div = $(this);
if (div.height() == div.scrollTop() + 1) //scrollTop is 0 based
{
alert('Reached the bottom!");
}
});
});
Edit: a little testing in a js fiddle and I realized the previous version is incorrect. You can use a DOM property to find out how much scrolling there is a perform a little math with the height of the element like so
编辑:在 js 小提琴中进行了一些测试,我意识到以前的版本不正确。您可以使用 DOM 属性来找出有多少滚动,像这样对元素的高度进行一些数学运算
var div = $(this);
if (div[0].scrollHeight - div.scrollTop() == div.height())
{
alert('Reached the bottom!');
}
回答by user2513149
This worked for me (using jQuery):
这对我有用(使用 jQuery):
$(document).ready(function(){
$('div').scroll(function(){
//scrollTop refers to the top of the scroll position, which will be scrollHeight - offsetHeight
if(this.scrollTop == (this.scrollHeight - this.offsetHeight)) {
console.log("Top of the bottom reached!");
}
});
});
Taken from here.
取自这里。
回答by ShankarSangoli
You can check if the element scrollTop
is equal to the element innerHeight
.
您可以检查元素scrollTop
是否等于元素innerHeight
。
if($('div').scrollTop() == $('div').innerHeight()){
//Reached the bottom
}