在JavaScript中,可以使用以下方法实现无限滚动:

  1. 监听滚动事件:使用addEventListener方法监听滚动事件,当滚动到页面底部时触发加载新内容的函数。
window.addEventListener('scroll', function() {
  if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    // 这里触发加载新内容的函数
  }
});
  1. 发送异步请求获取新内容:在滚动到页面底部时,发送异步请求获取新的内容。可以使用XMLHttpRequest对象或者fetch函数来发送请求。
function loadNewContent() {
  // 发送异步请求获取新内容
  fetch('https://example.com/new-content')
    .then(response => response.json())
    .then(data => {
      // 处理获取的新内容
    });
}
  1. 添加新内容到页面:在获取到新的内容后,将新内容添加到页面中。可以使用appendChild方法将新的DOM元素添加到页面中。
function loadNewContent() {
  fetch('https://example.com/new-content')
    .then(response => response.json())
    .then(data => {
      // 处理获取的新内容
      data.forEach(item => {
        const newElement = document.createElement('div');
        newElement.innerText = item;
        document.body.appendChild(newElement);
      });
    });
}

通过以上步骤,就可以实现无限滚动效果。每当滚动到页面底部时,就会加载新的内容并添加到页面中

js怎么做无限滚动

原文地址: https://www.cveoy.top/t/topic/iygO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录