js判断一个元素是否在可视区内

html

<style>
    * {
      padding: 0;
      margin: 0;
    }

    header,
    main,
    footer {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container,
    .footer {
      height: 1000px;
      width: 100%;
    }

    .main {
      height: 300px;
      width: 100%;
    }
  </style>
</head>

<body>
  <header class="container">
    <span>header</span>
  </header>
  <main class="main">
    <span>content</span>
  </main>
  <footer class="footer">
    <span>footer</span>
  </footer>
  
</body>

方法1

function isInViewport(element) {
    // 使用getBoundingClientRect()方法:这个方法返回一个DOM元素的位置信息,包括元素的顶部、底部、左侧和右侧相对于视口的坐标。通过比较元素的位置信息和视口的大小,可以判断元素是否在可视区内。
    const rect = element.getBoundingClientRect();
    const windowHeight =
      window.innerHeight || document.documentElement.clientHeight;
    const windowWidth = window.innerWidth || document.documentElement.clientWidth;

    // 判断元素上下左右边界是否都在可视区内
    const isInsideViewport =
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= windowHeight &&
      rect.right <= windowWidth;

    return isInsideViewport;
  }

  // 使用示例:
  // console.log(isInViewport(element)); // 返回true或false
  const element = document.querySelector('.main')
  document.addEventListener('scroll', function() {
    // console.log(123);
    console.log(isInViewport(element)); // 返回true或false
  })

方法2

// 使用Intersection Observer API:这是现代浏览器提供的一个API,用于监测目标元素与其祖先元素或视口的交叉状态。
    // 通过创建一个IntersectionObserver实例,并设置回调函数,可以判断元素是否进入或离开可视区。
    const options = {
      root: null,
      rootMargin: '0px',
      threshold: 0.5
    };

    function callback(entries, observer) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          console.log(entry.target.id + ' 进入可视区');
        } else {
          console.log(entry.target.id + ' 离开可视区');
        }
      });
    }

    const observer = new IntersectionObserver(callback, options);

    // 使用示例:
    const element = document.querySelector('.main');
    // observer.observe(element);
    // wheel 滚轮时间
    document.addEventListener('wheel', function() {
      observer.observe(element);
    })

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值