10行代码借助js原生api实现触底加载

190 阅读1分钟

Intersection Observer

new一个 Intersection Observer 对象时,会返回一个实例,可以通过这个实例监听某个元素与设备视窗或者其他指定元素是否发生交集,我们可以借助这个 api 实现页面滚动触底加载。

简单实现基本 css 样式

<style>
  .box {
    width: 300px;
    height: 600px;
    box-sizing: border-box;
    padding: 10px 10px 0;
    background-color: red;
    overflow: scroll;
  }
  .item {
    height: 285px;
    margin-bottom: 10px;
    background-color: skyblue;
  }
</style>
<div class="box">
  <div class="item-content">
    <div class="item"></div>
  </div>
  <div class="bottom"></div>
</div>

js 逻辑

<script>
  const container = document.querySelector(".item-container")
  const bottom = document.querySelector(".bottom")
  
  const obs = new IntersectionObserver((e) => {
    // 判断指定元素是否在根元素(默认是父元素)可见
    if(e[0].isIntersecting) {
      for(let i = 0; i < 5; i++) {
        const div = document.createElement("div")
        div.className = "item"
        container.appendChild(div)
      }
    }
  })
  
  // 调用实例的 observe() 方法,开启监听 bottom 元素的可见区域是否超过根元素的可见区域阈值
  // 阈值可以通过 IntersectionObserver 实例的第二个参数配置
  obs.observe(bottom)
</script>
  • IntersectionObserver 支持传入两个参数,一个为回调(必传),另一个为配置(可选)
  • 被监听元素相对于根元素(默认是被监听元素的父元素)可见时,会执行回调
  • 如果想实现距离底部 200px 时执行回调,可以给被监听的元素 bottom 设置高度为 200px

浏览器兼容

options.rootIntersectionObserver 的第二个参数(可选)的配置

图片来自于 mdn社区: 点击链接进入 image.png

本文只介绍了 Intersection Observer api的简单使用,更详细的使用可以去 mdn 社区阅读文档: developer.mozilla.org/zh-CN/docs/…