如何确定用户何时滚动到容器div的底部?对于无限滚动

时间:2013-12-26 15:56:40

标签: javascript jquery html infinite-scroll

http://jsfiddle.net/leonwho/L9A6Q/

我正在准备在我们网站的仪表板上开发无限滚动,但是我现在停留在如何确定jsfiddle mockup中容器div的底部。

enter image description here

原始功能,适用于没有容器div的空白页

var wireInfinScroll = function() {

    console.log('in wireInfinScroll');

    $('#scroll_screen').scroll(function(){

        console.log('scrolling...');
        console.log(' ');

        //if ($('#scroll_screen').scrollTop() == $('#content').height() -     $('#scroll_screen').outerHeight()) {

        if ($('#scroll_screen').scrollTop() == $('#content').height() - $('#scroll_screen').height()) {
            // run our call for pagination
            console.log('Bottom of Page!');
            alert('Bottom of Page!');
        }
    });
}

wireInfinScroll();

CSS

#scroll_screen {
  overflow-y: auto;
  background: pink;
}

我尝试在我的示例中使用滚动的div(window)替换#scroll_screen,但无法触发警报。

你怎么能解决这个问题?


更新

  • 注意,我在这里使用相同的代码创建了一个新的jsFiddle: http://jsfiddle.net/leonwho/L9A6Q/

  • 此外,我注意到我的console.logs从未显示,除非我点击内部 #scroll_screen div?

  • 删除了Codepen,使用$('#scroll_screen').scroll(function(){

  • 进一步了解jsFiddle
  • 请注意!当我从height: 100% div中删除#content时,向下滚动并备份我最终获得提醒,但这仍然不正确。 警告应该在向下滚动

  • 时发生

CSS

   #content {
     float: right;
     width: 79%;
     //height: 100%;
     background: #f8f8f8;
   }

2 个答案:

答案 0 :(得分:1)

$('#scroll_screen').height() - $('#content').height()会给出一个负值,因为scroll_screen的高度始终小于content的高度,这意味着scroll_screen的{​​{1}}永远不会等于负值,所以替换

scrollTop

$('#scroll_screen').scrollTop() == $('#scroll_screen').height() - $('#content').height()

(大于或等于动画跳过它的情况。)

[编辑]我注意到它滚动到$('#scroll_screen').scrollTop() >= if ( $('#scroll_screen').scrollTop() >= -($('#content').height() - $('#scroll_screen').height()) )) ,因此200应该有效。

答案 1 :(得分:1)

您只需在滚动方法中检查(滚动距离+窗口高度)> =(元素的偏移顶部+高度)。

在这种情况下,例如:

$(window).scroll(function(){
  if( ($(document).scrollTop() + $(window).height()) >= ($('#yourElement').offset().top + $('#yourElement').height()){
    // Bottom of the element reached :)
  }
});