IntersectionObserver在root为视口的情况下,rootMargin设置失效

1.背景
在使用IntersectionObserver实现懒加载时,想要通过设置rootMargin去设置某个元素滚动到距离视口一定距离时再加载,按照MDN上IntersectionObserver的定义来看,应该是可以的
2.现象
现在是我把root设置为null(即视口)的时候,rootMargin虽然设置了50px,实际观察下来,仍然在0px的时候触发了加载
3.代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title>测试IntersectionObserver</title>

    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        background: #eee;
        font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #000;
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .container {
        margin: auto;
        width: 100%;
        height: 500px;
        border: 1px solid red;
        overflow-x: auto;
      }
      .list {
        width: 200vw;
        height: 500px;
        border: 1px solid blue;
        box-sizing: border-box;
        padding-left: 100px;
      }
      .listItem {
        width: 100px;
        height: 100px;
        background: white;
      }
    </style>
  </head>
  <body>
    <div class="container" id="container">
      <div class="list" id="list">
        <div class="listItem" id="listItem"></div>
      </div>
    </div>
    <script>
      // document.querySelector("#container").style.width =
      //   window.innerWidth + "px";
      let callback = (entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            console.log("出现");
          } else {
            console.log("消失");
          }
        });
      };
      let options = {
        // root: document.querySelector("#container"), // root为container时rootmargin生效
        root: null, // root为null时rootmargin不生效
        rootMargin: "0px 50px",
        threshold: 0,
      };

      let observer = new IntersectionObserver(callback, options);
      let target = document.querySelector("#listItem");
      observer.observe(target);
    </script>
  </body>
</html>

4.问题
所以root为视口的时候,是不能直接通过设置rootmargin去扩大视口边距的吗,只能间接通过设置一层父级去触发吗

阅读 4.9k
1 个回答

rootMargin 跟 CSS 盒模型的 Margin 不一样(方位一样,正负值不一样)
rootMargin: "0px 50px" 的意思是,左右视口增大50px, 上下视口不变
如果你想要增大上下视口 50px 的话,应该用 rootMargin: "50px 0px"
建议阅读一下文章:

补充回答:

  1. 如果是刚好想左右视口增加50px的话,这种表现是正确的,因为这时 IntersectionObserver 观察的范围就是其实是整个视口加上左右两边看不到的50px的增幅,你的观察对象一开始就已经在这个范围了(视口里面),你可以尝试左右滑动过去,可以观察到会触发消失,滑动回来,然后触发出现。
  2. 建议设置的观察视口是上一级的可滚动的元素,因为如果root是视口而且上一级有滚动元素的时候会有一些问题。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题