我有一个div框(称为flux),里面有可变数量的内容。
此divbox已将溢出设置为自动。
现在,我要做的是,当使用滚动到这个div框的底部,加载更多的内容到页面,我知道如何做到这一点(加载内容),但我不知道如何检测当用户已经滚动到div标签的底部?
如果我想对整个页面都这样做,我将使用。scrolltop并从。height中减去它。
但我在这里好像做不到?
我已经尝试从通量。scrolltop,然后包装内的所有内容在一个div称为内部,但如果我采取通量的innerHeight它返回564px (div被设置为500作为高度)和“内部”的高度它返回1064,而滚动顶部,当在div的底部说564。
我该怎么办?
虽然这个问题是在5.5年前提出的,但在今天的UI/UX环境中,它仍然非常相关。我想补充一下我的意见。
var element = document.getElementById('flux');
if (element.scrollHeight - element.scrollTop === element.clientHeight)
{
// element is at the end of its scroll, load more content
}
来源:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight Determine_if_an_element_has_been_totally_scrolled
有些元素不允许滚动元素的整个高度。在这些情况下,你可以使用:
var element = docuement.getElementById('flux');
if (element.offsetHeight + element.scrollTop === element.scrollHeight) {
// element is at the end of its scroll, load more content
}
如果你没有使用Math.round()函数,Dr.Molle建议的解决方案在某些情况下当浏览器窗口有缩放时将不起作用。
例如
$(this).scrollTop() + $(this).innerHeight() = 600
(美元)[0]。scrollHeight yield = 599.99998
600 >= 599.99998失败。
下面是正确的代码:
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
alert('end reached');
}
})
});
如果你不需要一个严格的条件,你也可以添加一些额外的边缘像素
var margin = 4
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
alert('end reached');
}
})
});
这是另一个版本。
The key code is function scroller() which takes input as the height of the div containing the scrolling section, using overflow:scroll. It approximates 5px from the top or 10px from the bottom as at the top or bottom. Otherwise it's too sensitive. It seems 10px is about the minimum. You'll see it adds 10 to the div height to get the bottom height. I assume 5px might work, I didn't test extensively. YMMV. scrollHeight returns the height of the inner scrolling area, not the displayed height of the div, which in this case is 400px.
<?php
$scrolling_area_height=400;
echo '
<script type="text/javascript">
function scroller(ourheight) {
var ourtop=document.getElementById(\'scrolling_area\').scrollTop;
if (ourtop > (ourheight-\''.($scrolling_area_height+10).'\')) {
alert(\'at the bottom; ourtop:\'+ourtop+\' ourheight:\'+ourheight);
}
if (ourtop <= (5)) {
alert(\'Reached the top\');
}
}
</script>
<style type="text/css">
.scroller {
display:block;
float:left;
top:10px;
left:10px;
height:'.$scrolling_area_height.';
border:1px solid red;
width:200px;
overflow:scroll;
}
</style>
$content="your content here";
<div id="scrolling_area" class="scroller">
onscroll="var ourheight=document.getElementById(\'scrolling_area\').scrollHeight;
scroller(ourheight);"
>'.$content.'
</div>';
?>