JS判断元素是否在可视区域中

JS如何判断一个元素是否在可视区域中?下文分解。

方法一:利用 scrollTopoffsetTopclientHeight 的关系

/**
 * 利用 offsetTop <= clientHeight + scrollTop;
 * @param element
 * @returns
 */
export const isInViewPort = element => {
  // clientHeight 兼容所有浏览器写法
  const clientHeight =
    window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  const offsetTop = element.offsetTop;
  const scrollTop = document.documentElement.scrollTop;
  return offsetTop <= clientHeight + scrollTop;
};

方法二:通过getBoundingClientRect的top、left、right、bottom属性判断元素的位置是否在可视区域

/**
 * 通过getBoundingClientRect的top、left、right、bottom属性判断元素的位置是否在可视区域
 * @param element
 * @returns
 */
export const isInViewPort = element => {
  const viewWidth =
    window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  const viewHeight =
    window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

  const { top, right, bottom, left } = element.getBoundingClientRect();

  return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
};

方法三:使用 IntersectionObserver 对象(性能最佳,推荐使用)

  • IntersectionObserver 的原理基于浏览器的布局引擎和事件循环机制。它通过浏览器内部的优化机制来高效地检测元素与其祖先元素(或视口)之间的交叉状态变化
  • 以下是 React 使用例子
import React, { useRef, useLayoutEffect, useState } from "react";

const MyComponent = () => {
  const [isVisible, setIsVisible] = useState(false);
  const bottomRef = useRef<HTMLDivElement | null>(null);

  useLayoutEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        // isIntersecting:两个元素矩阵相交且占标记元素的设定比例时为true,表示元素在视口中
        if (entries[0].isIntersecting) {
          setIsVisible(true);
        } else {
          setIsVisible(false);
        }
      },
      {
        root: null, // 使用视口作为根,当然也可以指定一个元素
        rootMargin: "0px",
        threshold: 0.1, // 当标记元素至少有10%进入视口时触发回调
      }
    );

    if (bottomRef.current) {
      observer.observe(bottomRef.current);
    }

    return () => {
      if (bottomRef.current) {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        observer.unobserve(bottomRef.current);
      }
    };
  }, []);

  return (
    <div>
      <div style={{ position: "fixed", top: "40vh", left: 0, width: '100vw', textAlign: 'center' }}>
        {isVisible ? "Element is in view" : "Element is out of view"}
      </div>
      <div style={{ height: "150vh" }}>Scroll down to see the element</div>
      <div
        ref={bottomRef}
        style={{ height: "100px", backgroundColor: "lightblue" }}
      />
    </div>
  );
};

export default MyComponent;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值