如何监听div内容滚动到底部事件 实现Ajax加载更多商品功能
内部div滚动监听加载解决方案
错误原因
你之前的代码监听的是全局window的滚动事件,而你的页面整体固定无滚动,滚动行为发生在内部的.product-list-item容器上,因此事件绑定对象、高度计算逻辑都不匹配,自然无法触发。
实现步骤
1. 先给滚动容器加必要样式
首先要确保你的商品列表容器设置了固定高度和纵向滚动属性,否则不会触发滚动事件:
.product-list-item { /* 按你的页面布局调整高度,比如减去顶部导航、底部标签栏的高度 */ height: calc(100vh - 120px); overflow-y: auto; /* 其他原有样式保留 */ }
2. jQuery版本实现(和你原有技术栈匹配)
核心逻辑是监听滚动容器自身的滚动事件,计算滚动位置是否接近底部,同时加加载锁避免重复请求:
// 获取滚动容器 const $scrollContainer = $('.product-list-item'); // 加载状态锁,避免滚动时重复发送请求 let isLoading = false; // 自行维护请求页码 let nextPage = 1; // 绑定容器自身的滚动事件 $scrollContainer.scroll(function() { if (isLoading) return; const scrollTop = $scrollContainer.scrollTop(); // 容器可视区域高度 const containerViewHeight = $scrollContainer.innerHeight(); // 容器内部内容的总高度 const contentTotalHeight = $scrollContainer[0].scrollHeight; // 距离底部还有10px时触发加载,可自行调整这个阈值优化体验 if (scrollTop + containerViewHeight >= contentTotalHeight - 10) { isLoading = true; // 你的AJAX请求逻辑 $.ajax({ url: '你的商品接口地址', method: 'GET', data: { page: nextPage, // 其他请求参数 }, success: function(res) { // 将返回的商品卡片DOM追加到容器末尾 $scrollContainer.append(res.productHtml); // 页码+1,加载状态重置 nextPage++; isLoading = false; }, error: function() { // 请求失败也要重置加载状态,方便后续重试 isLoading = false; } }) } })
3. 原生JS版本实现(不需要jQuery的场景)
如果项目没有引入jQuery,可以用原生API实现,逻辑一致:
const scrollContainer = document.querySelector('.product-list-item'); let isLoading = false; let nextPage = 1; scrollContainer.addEventListener('scroll', () => { if (isLoading) return; const scrollTop = scrollContainer.scrollTop; const containerViewHeight = scrollContainer.clientHeight; const contentTotalHeight = scrollContainer.scrollHeight; if (scrollTop + containerViewHeight >= contentTotalHeight - 10) { isLoading = true; fetch('你的商品接口地址?page=' + nextPage) .then(res => res.json()) .then(data => { scrollContainer.insertAdjacentHTML('beforeend', data.productHtml); nextPage++; isLoading = false; }) .catch(err => { isLoading = false; }) } })
注意事项
- 阈值可以根据你的需求调整,设置为50~100px可以提前触发加载,用户几乎感知不到等待过程,体验更接近原生应用
- 如果商品加载完没有更多数据了,可以加个
noMore标识,触发时直接返回,不再发送请求
内容的提问来源于stack exchange,提问作者Aditya Rizqi
相关产品推荐
相关产品推荐

