【JS】监听元素重叠

常见场景: 滚动条滚动到底部时加载数据,如果监听滚动事件,会造成不必要的浪费。如频繁滚动但未达底部。可以建立观察者,监听loading标识元素到达视口某位置后再加载数据。

步骤

创建一个新的 IntersectionObserver 对象,当其监听到目标元素的可见部分(的比例)超过了一个或多个阈值(threshold)时,会执行指定的回调函数。

  • 创建观察者:new IntersectionObserver(),接受两个参数
    • 参数1:回调函数
      参数entries观察的所有元素的集合。被观察元素的isIntersecting属性为true时表示已超过重叠阈值
    • 参数2:构造器
      root为与被观察元素重叠的元素,默认为null,表示顶级文档视口。thresholds表示阈值,小数表示百分比,即重叠比例,默认为0。
  • 观察元素:IntersectionObserver.observe(),一个观察者可以观察多个元素,当观察多个元素时,参数1中的entries也为多个。
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll Loading</title>
  <style>
    .content {
      height: 800px;
      overflow-y: scroll;
      padding: 20px;
      border: 1px solid #333;
    }

    .box {
      width: 100%;
      height: 400px;
      background-color: #bfd;
      margin-bottom: 30px;
    }

    #loading {
      display: block;
      text-align: center;
      padding: 10px;
      background-color: #f1f1f1;
      margin-top: 10px;
    }

    .hidden {
      display: none;
    }
  </style>
</head>

<body>
  <div class="content">
    <div class="box">1</div>
    <div class="box">1</div>
    <div class="box">1</div>
    <div class="box">1</div>
    <div id="loading" class="hidden">Loading...</div>
  </div>
  <script>
    // 建立观察者
    const loading = document.getElementById('loading');
    let ob = new IntersectionObserver(function (entries) {
      let loading = entries[0]
      console.log(loading.isIntersecting);
      if (loading.isIntersecting) {
        console.log('加载更多');
      }
    }, {
      thresholds: 0.5
    })
    ob.observe(loading);

  </script>
</body>

</html>
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值