下面的代码将内容添加到DIV,然后滚动它以显示新内容:
<div id="Scrollable" style="height:400px; overflow:scroll;>
1<br />
2<br />
3<br />
4<br />
</div>
<script>
// Should DIV be auto scrolled?
var autoScroll = true;
// Add new content
$('#Scrollable').append('5<br />6<br />');
if ( autoScroll ){ // Scroll to bottom of DIV
$('#Scrollable').animate({ scrollTop: $('#Scrollable').prop('scrollHeight') });
}
</script>
我需要的是在var autoScroll = true
阶段检查以检测DIV当前是否滚动到底部。因此,添加新内容后,只会在DIV位于底部之前自动滚动。
答案 0 :(得分:4)
尝试写这个时遇到了什么问题?这是一个jsFiddle示例,基于我在Google中找到的第一个结果&#34; jquery检查div是否滚动到底部&#34;。它似乎工作正常。
这里是我发现的文章的链接:http://www.yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/
编辑:这里是我发布的jsFiddle的实际代码,以防有人搜索和jsFiddle消失。有一个可滚动的div(给它一个高度和overflow-y: scroll
),id为可滚动,内部div有一个内部类。然后,您可以使用以下代码确定div是否滚动到底部:
var scrollable = $('#scrollable');
var inner = $('#scrollable > .inner');
// check if div is scrolled to bottom before addition of new content
var atBottom = Math.abs(inner.offset().top) + scrollable.height() + scrollable.offset().top >= inner.outerHeight();
// add additional content to .inner here
if ( atBottom ) {
// do stuff like scroll to bottom etc
}
答案 1 :(得分:0)
There's a good example of this listed here.
The following equivalence returns true if an element is at the end of its scroll, false if it isn't.
element.scrollHeight - element.scrollTop === element.clientHeight
The demo listed on that page is very helpful as well.