简单了解下 IntersectionObserver的rootMargin!

看到蛮多写IntersectionObserver的博客的,但是感觉里面关键部分都介绍的模棱两可,所以我来简单说说这个。至于什么是IntersectionObserver,官网上有 IntersectionObserver,我就不去一一阐述了,下面说最关键的点和使用场景!

javascript 复制代码
    new IntersectionObserver(
        function (entries) {
          // entries[0].isIntersecting
        },
        {
          rootMargin: "0px 0px 0px 0px"
        }
      )

关键点

设置上边距,当前元素的下边框监测会更早出现更晚消失。

设置下边距,当前元素的上边框监测会更早出现更晚消失。

并且rootMargin必须要设置px或者百分比,这百分比是相对视口高度来说的,所以说一般建议使用px,如:"30px 0px 0px 0px" 或者 "10% 0px 0px 0px",必须要带px,不能只写数值否则无效

场景

有预懒加载的地方大概率会使用到IntersectionObserver,比如向上滑动时,如果图片或者其他dom比较多时,当滑到才渲染可能来不及,所以需要提前一段距离就开始渲染

示例源码

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IntersectionObserver-rootMargin</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      .white-dom {
        height: 710px;
      }
      #target {
        background: rgb(237, 28, 36);
        height: 100px;
        outline: 33px solid rgba(0, 0, 0, 0.2);
      }
      #info {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 2rem;
      }
    </style>
  </head>
  <body>
    <div class="white-dom"></div>
    <div id="target"></div>
    <div class="white-dom"></div>
    <span id="info">初始化</span>
    <script>
      const io = new IntersectionObserver(
        function (entries) {
          console.log('IntersectionObserver触发');
          document.getElementById("info").innerHTML = entries[0].isIntersecting
            ? "元素显示"
            : "元素隐藏";
        },
        {
          rootMargin: "0px 0px 33px 0px"
        }
      );
      io.observe(document.getElementById("target"));
    </script>
  </body>
</html>
相关推荐
2301_7969821414 分钟前
网页打开时,下载的文件text/html/重定向类型有什么作用?
前端·html
重生之我在20年代敲代码15 分钟前
HTML讲解(二)head部分
前端·笔记·html·web app
天下无贼!21 分钟前
2024年最新版TypeScript学习笔记——泛型、接口、枚举、自定义类型等知识点
前端·javascript·vue.js·笔记·学习·typescript·html
小白小白从不日白1 小时前
react 高阶组件
前端·javascript·react.js
Mingyueyixi1 小时前
Flutter Spacer引发的The ParentDataWidget Expanded(flex: 1) 惨案
前端·flutter
Rverdoser2 小时前
unocss 一直热更新打印[vite] hot updated: /__uno.css
前端·css
Bang邦3 小时前
使用nvm管理Node.js多版本
前端·node.js·node多版本管理
podoor3 小时前
wordpress不同网站 调用同一数据表
前端·wordpress
LJ小番茄3 小时前
Vue 常见的几种通信方式(总结)
前端·javascript·vue.js·html
黑狼传说3 小时前
前端项目优化:极致最优 vs 相对最优 —— 深入探索与实践
前端·性能优化