useElementVisibility

追踪視窗内元素可見性的 React Hook。这是 useIntersectionObserver 的一个封装器

useElementVisibility 追蹤一個 DOM 元素是否在視窗中可見,使用 Intersection Observer API。它回傳一個布林值,在元素進入或離開視窗時更新。

使用場景

  • 實作延遲載入——在元素進入視窗時載入圖片或內容
  • 當元素可見時觸發進入動畫
  • 追蹤廣告或內容區塊的可見性以記錄曝光次數

注意事項

  • SSR 安全:在伺服器端渲染時回傳 false。伺服器上不會建立 IntersectionObserver
  • 閾值:可透過選項設定可見性閾值,以控制元素需要多少部分可見才觸發。
  • 相關 hooks:另請參閱 useIntersectionObserver 用於更低階的 Intersection Observer 存取。

Usage

Live Editor

function Demo() {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, stop] = useElementVisibility(ref);

  return (
    <div>
      <p>右下角的信息</p>
      <div
        ref={ref}
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
        }}
      >
        目標元素(向下滾動)
      </div>
      <button
        onClick={() => {
          stop();
        }}
      >
        停止
      </button>
      <div
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
          position: "fixed",
          bottom: 0,
          right: 0,
          zIndex: 100,
        }}
      >
        元素 {visible ? "在視窗內" : "在視窗外"}
      </div>
    </div>
  );
};
Result

API

useElementVisibility

Returns

readonly [boolean, () => void]: 包含以下元素的元組:

  • 當前元素是否可見。
  • 停止監聽函數。

Arguments

參數名描述類型預設值
targetdom对象BasicTarget<HTMLElement | SVGElement> (必填)-
options传递给 intersectionObserver 的选项IntersectionObserverInit | undefined-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;