> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# 可见性检测

Lynx 提供了两种检测节点可见性的能力，一种是 Lynx 独有的曝光能力，开发者可以据此便捷地监听节点是否曝光；另一种是类 Web 的交叉观察器，这是一种更加原子的能力，开发者可以通过它来监听节点的交叉位置。

## 检测节点是否曝光

当开发者主要关注多个节点是否在屏幕上而不关注节点交叉位置，并且希望快速地编写代码时，可以使用[曝光能力](/next/zh/guide/interaction/visibility-detection/exposure-ability.md)。

[曝光能力](/next/zh/guide/interaction/visibility-detection/exposure-ability.md)是一个声明式接口，开发者可以通过 [`exposure-id`](/next/zh/api/elements/built-in/view.md#exposure-id) 属性来指定需要监听曝光的节点，当节点出现时，会触发曝光事件 `exposure`，当节点消失时，会触发反曝光事件 `disexposure`。

在下面这个例子中，开发者监听节点是否曝光/反曝光，实时显示在屏幕上可见的节点 [`exposure-id`](/next/zh/api/elements/built-in/view.md#exposure-id)。

**示例 2:**

**下面是一个示例: event**

**Entry:** `src/visibility_expose`
**Bundle:** `dist/visibility_expose.lynx.bundle` | Web: `dist/visibility_expose.web.bundle`

```tsx {8-12,14-21,62}
import { root, useState } from "@lynx-js/react";
import { useLynxGlobalEventListener } from "@lynx-js/react";

export default function App() {
  const [eventLog, setEventLog] = useState<string>("");

  useLynxGlobalEventListener("exposure", (e) => {
    (e as { "exposure-id": string }[]).forEach((item) => {
      setEventLog((log) => log + (log === "" ? "" : ", ") + item["exposure-id"]);
    });
  });

  useLynxGlobalEventListener("disexposure", (e) => {
    let log = eventLog.split(", ");
    (e as { "exposure-id": string }[]).forEach((item) => {
      log = log.filter(id => id !== item["exposure-id"]);
    });
    log.sort();
    setEventLog(log.join(", "));
  });

  return (
    <view
      style={{ width: "100%", height: "90%" }}
    >
      <view
        style={{
          width: "calc(100% - 10px)",
          height: "150px",
          margin: "5px",
          borderWidth: "2px",
        }}
      >
        <text>Exposed node:</text>
        <text style={{ color: "red" }}>{eventLog}</text>
      </view>
      <scroll-view
        scroll-orientation="vertical"
        style={{
          width: "100%",
          height: "calc(100% - 165px)",
          backgroundColor: "yellow",
          marginTop: "15px",
          paddingTop: "40px",
        }}
        id="container"
      >
        {[0, 1, 2, 3, 4, 5, 6].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "150px",
                margin: "5px",
                backgroundColor: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${
                  Math.floor(Math.random() * 256)
                })`,
                borderRadius: "5px",
                alignItems: "center",
              }}
              exposure-id={`scroll-item-${item + 1}`}
            >
              <text>scroll-item-{item + 1}</text>
            </view>
          );
        })}
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>scroll container</text>
        </view>
      </scroll-view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.7.0



由于曝光能力侧重于节点是否可见，因此，这里的节点可见性要求更加严格。另外，由于[曝光能力](/next/zh/guide/interaction/visibility-detection/exposure-ability.md)是一个声明式接口，当开发者需要监听多个节点的曝光时，只需要在节点上添加 [`exposure-id`](/next/zh/api/elements/built-in/view.md#exposure-id) 属性即可。

## 检测节点是否交叉

当开发者只需要检查节点之间是否交叉，而不关心节点是否在屏幕上时，可以使用[交叉观察器](/next/zh/guide/interaction/visibility-detection/intersection-observer.md)。

[交叉观察器](/next/zh/guide/interaction/visibility-detection/intersection-observer.md)用于检测目标节点与参照节点及目标节点与祖先节点之间是否交叉，开发者可以灵活地指定参照节点、参照节点边界缩放值、节点交叉比例阈值等，进而实现更加灵活的节点可见性定义。

在下面这个例子中，开发者监听父节点与子节点是否交叉，并在交叉时输出交叉的子节点 [`id`](/next/zh/api/elements/built-in/view.md#id) 和交叉的位置。

**示例 1:**

**下面是一个示例: event**

**Entry:** `src/visibility_intersection`
**Bundle:** `dist/visibility_intersection.lynx.bundle` | Web: `dist/visibility_intersection.web.bundle`

```tsx {8-24}
import { root, useState } from "@lynx-js/react";
import type { IntersectionObserver, ObserveCallbackResult, TouchEvent } from "@lynx-js/types";

export default function App() {
  const [eventLog, setEventLog] = useState<string>("");
  let observer: IntersectionObserver | null = null;

  function handleTap(e: TouchEvent) {
    "background only";
    setEventLog("");
    if (observer == null) {
      observer = lynx.createIntersectionObserver({ componentId: "" }, { thresholds: [] });
      observer.relativeTo("#container");
      for (let i = 1; i <= 7; i++) {
        observer.observe("#view-item-" + i, (res: ObserveCallbackResult) => {
          if (res.isIntersecting) {
            let rect = res.intersectionRect;
            let rect_str = ", location: [" + rect.left + ", " + rect.top + ", " + rect.right + ", " + rect.bottom + "]";
            setEventLog((log) => log + (log === "" ? "node: " : "\nnode: ") + res.observerId + rect_str);
          }
        });
      }
    }
  }

  return (
    <view
      style={{ width: "100%", height: "90%", overflow: "hidden" }}
      bindtap={(e) => {
        handleTap(e);
      }}
    >
      <view
        style={{
          width: "calc(100% - 10px)",
          height: "150px",
          margin: "5px",
          borderWidth: "2px",
        }}
      >
        <text>Click the page to get intersected nodes:</text>
        <text style={{ color: "red" }}>{eventLog}</text>
      </view>
      <view
        style={{
          width: "100%",
          height: "calc(100% - 165px)",
          paddingTop: "40px",
          marginTop: "15px",
          backgroundColor: "yellow",
        }}
        id="container"
      >
        {[0, 1, 2, 3, 4, 5, 6].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "150px",
                margin: "5px",
                borderRadius: "5px",
                backgroundColor: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${
                  Math.floor(Math.random() * 256)
                })`,
                alignItems: "center",
              }}
              id={`view-item-${item + 1}`}
            >
              <text>view-item-{item + 1}</text>
            </view>
          );
        })}
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>view container</text>
        </view>
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.7.0



这里的节点可见性只要求目标节点和参照节点交叉即可，而不需要目标节点在屏幕上，并且也不需要指定参照节点为滚动容器。另外，由于[交叉观察器](/next/zh/guide/interaction/visibility-detection/intersection-observer.md)是一个命令式接口，当开发者需要监听多个节点的交叉时，需要冗余的代码编写。

## 总结

至此，你已经学会了如何检测节点之间是否交叉或者节点是否曝光。

对于开发者来说，当重点关注节点是否在屏幕上，并且希望便捷地编写多个节点曝光监听的代码时，可以使用[曝光能力](/next/zh/guide/interaction/visibility-detection/exposure-ability.md)；当重点关注节点之间是否交叉和交叉的位置，或者需要灵活的定义节点的可见性时，可以使用[交叉观察器](/next/zh/guide/interaction/visibility-detection/intersection-observer.md)。
