滚动到页面底部或div时如何运行一个功能?

How to run a function when scrolling to the bottom of the page or div?

我想知道如何在通过溢出滚动到达 div 末尾时执行 javascript 函数。我的情况是这样的,我希望当用户看到所有的帖子都是这样排列的div,到达所有内容的末尾时,通过ajax加载更多的内容,这就是我想要的功能向下滚动时 运行。

试试这个,滚动到底部后会显示一个警告框(向上滚动后会消失):

$('.watch-scroll').on('scroll', function(e){
  var t = $(this);
  if(t[0].scrollHeight - t.scrollTop() - t.outerHeight() < 1){
    $('.alert').show();
  }else{
    $('.alert').hide();
  }
})
.watch-scroll {
  height: 100px;
  width:500px;
  overflow: auto;
  border:1px solid black;
}
.placeholder{
  height:300px; 
}
.alert{
  width:300px;
  padding:1em;
  color:white;
  background-color:#ff5c5c;
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="watch-scroll">
  <div class="placeholder"></div>
</div>
<div class="alert">You have scrolled to the bottom</div>

像上一个答案一样添加滚动事件是可行的,但如果您希望获得最佳性能,则应使用 IntersectionObserver

<div class="container">
  <div class="scrollable">
    ... All Visible Content Here ...
    <div class="scroll-bottom"></div>
  </div>
</div>

在这个例子中,使非零高度的.scroll-bottom在最底部,并使用Javascript在其上附加一个IntersectionObserver。然后等到它与 container 相交,你就会知道它已经滚动到视图中,这意味着你已经滚动到底部。

您可以使用类似的方法来滚动页面,但您可以简单地检测与 viewport.

的交集

您可以进一步阅读有关 IntersectionObserver 的内容,因为它的实施并非易事。

当然,如果性能不重要,您可以按照其他答案的建议使用滚动监听器。