Next, implement the function of scrolling to load more content in the JavaScript filemain.js
.
// 获取显示内容的容器元素 const contentContainer = document.getElementById('content'); // 监听滚动事件 contentContainer.addEventListener('scroll', function() { // 判断用户是否滚动到底部 if (contentContainer.scrollTop + contentContainer.clientHeight >= contentContainer.scrollHeight) { // 模拟异步请求加载更多内容 setTimeout(function() { // 创建新的内容元素 const newContent = document.createElement('p'); newContent.textContent = '加载的新内容'; // 将新的内容添加到容器中 contentContainer.appendChild(newContent); }, 1000); // 延时1秒模拟请求 } });
In this code, we first obtain the In the example, we use the Summary: The above is the detailed content of How to use JavaScript to automatically load more content when scrolling to the bottom of a web page?. For more information, please follow other related articles on the PHP Chinese website!setTimeout
function to simulate an asynchronous request and add new content elements to the container after a delay of 1 second. The delay time can be modified according to the actual situation, or a real asynchronous request can be used.
Monitor scrolling events through JavaScript and implement the function of automatically loading more content based on the scrolling position. In actual applications, specific loading behaviors and styles can be customized according to needs. This infinite scrolling interaction method can improve user experience and reduce page loading time and traffic consumption when a large amount of content needs to be displayed.