可以通过判断滚动位置来判断是否触顶或触底,然后根据当前下标的增减来加载相应的数据。

首先,需要监听滚动事件,可以使用onscroll事件或者addEventListener方法来监听。

然后,可以使用scrollTop属性来获取滚动条距离顶部的距离,使用clientHeight属性来获取可视区域的高度,使用scrollHeight属性来获取滚动内容的总高度。

判断触顶的条件是滚动条距离顶部的距离等于0,即scrollTop === 0。此时可以加载当前下标减1的数据。

判断触底的条件是滚动条距离顶部的距离加上可视区域的高度等于滚动内容的总高度,即scrollTop + clientHeight === scrollHeight。此时可以加载当前下标加1的数据。

下面是一个示例代码:

let arr = [[4,4,,44],[2,3,3,2],[1,11,1,1,]];
let currentIndex = 0;

window.addEventListener('scroll', function() {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  let clientHeight = document.documentElement.clientHeight;
  let scrollHeight = document.documentElement.scrollHeight;

  if (scrollTop === 0) {
    // 触顶加载当前下标-1的数据
    if (currentIndex > 0) {
      currentIndex--;
      // 加载数据的逻辑
      console.log("加载当前下标-1的数据");
      console.log(arr[currentIndex]);
    }
  } else if (scrollTop + clientHeight === scrollHeight) {
    // 触底加载当前下标+1的数据
    if (currentIndex < arr.length - 1) {
      currentIndex++;
      // 加载数据的逻辑
      console.log("加载当前下标+1的数据");
      console.log(arr[currentIndex]);
    }
  }
});

在上述代码中,可以根据需要自定义加载数据的逻辑,例如使用Ajax请求加载数据,并更新页面内容


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

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