You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现div内滚动加载帖子(无需插件)

Scroll-Triggered Infinite Scroll with jQuery (No Plugins)

Here's a straightforward, plugin-free implementation to detect when a user scrolls near the bottom of your target div and automatically load more content:

Step-by-Step Implementation

First, ensure your target div has proper CSS to enable scrolling—without this, the scroll event won’t fire:

#post-container {
  max-height: 600px; /* Adjust to fit your layout */
  overflow-y: auto; /* Creates a vertical scrollbar when content overflows */
}

Then use this jQuery code to handle the scroll trigger and data loading:

$(document).ready(function() {
  // Target your post container
  const $postContainer = $('#post-container');
  // Prevent duplicate AJAX requests while loading
  let isLoading = false;
  // Track pagination (adjust based on your API's logic)
  let currentPage = 1;

  // Attach scroll event listener to the div
  $postContainer.on('scroll', function() {
    // Calculate key scroll metrics
    const scrollTop = $postContainer.scrollTop();
    const totalContentHeight = $postContainer[0].scrollHeight;
    const visibleContainerHeight = $postContainer[0].clientHeight;

    // Trigger load when user is 50px from the bottom (adjust threshold as needed)
    const bottomThreshold = 50;

    // Check if we're near the bottom AND not already loading
    if (scrollTop + visibleContainerHeight >= totalContentHeight - bottomThreshold && !isLoading) {
      isLoading = true; // Lock to avoid duplicate requests

      // Fetch next set of posts via AJAX
      $.ajax({
        url: '/your-post-endpoint', // Replace with your actual API URL
        method: 'GET',
        data: { page: currentPage + 1 }, // Pass next page number to your server
        success: function(response) {
          // Append new posts to the container
          $postContainer.append(response);
          
          // Update page counter and unlock loading
          currentPage++;
          isLoading = false;
        },
        error: function() {
          // Handle loading errors gracefully
          isLoading = false;
          alert('Oops, failed to load more posts. Try again later.');
        }
      });
    }
  });
});

Key Notes for Success:

  • Loading Flag: The isLoading variable is critical—it stops multiple overlapping AJAX requests when the user scrolls quickly.
  • Threshold Tuning: The bottomThreshold value (50px here) lets you trigger the load a little before the user hits the absolute bottom, making the experience feel more responsive. Adjust it to match your UX needs.
  • Pagination Logic: The currentPage variable assumes your API uses page-based pagination. If your server uses offsets or another method, tweak this part accordingly.
  • No More Content: To handle the end of your post feed, add a check in the AJAX success callback:
    if (response.length === 0) {
      $postContainer.off('scroll'); // Stop listening for scroll events
      $postContainer.append('<div class="no-more-posts">No more posts to show!</div>');
    }
    

内容的提问来源于stack exchange,提问作者user3704392

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:14:59