---
name: "createIntersectionObserver"
mode: "api"
versionRequirements:
  - { name: "基础库", version: "2.10.0" }
title: "ty.createIntersectionObserver - 创建并返回一个 IntersectionObserver 对象实例。在自定义组件或包含自定义组件的页面中，应使用 `this.createIntersectionObserver([options])` 来代替。"
---

## createIntersectionObserver

> [VERSION] 基础库 >= 2.10.0

### 描述

创建并返回一个 IntersectionObserver 对象实例。用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见。

### 参数

`Params`

| 参数 | 类型 | 必填 | 描述 |
| --- | --- | --- | --- |
| `component` | `any` | 是 | 自定义组件实例，不传时默认使用当前页面 |
| `options` | `any` | 否 | 配置项 |

### 返回值

无


### 示例代码

#### 创建 IntersectionObserver 监听元素可见性

```html
// index.tyml
<scroll-view scroll-y="{{true}}" class="container">
  <view class="placeholder">向下滚动</view>
  <view class="target">观察目标</view>
</scroll-view>
<view class="status">{{visible ? '可见' : '不可见'}}</view>
```

```js
// index.js
Page({
  data: {
    visible: false,
    observer: null,
  },
  onReady() {
    var observer = ty.createIntersectionObserver(this, {
      thresholds: [0, 0.5, 1],
    });
    observer.relativeToViewport().observe('.target', (res) => {
      this.setData({ visible: res.intersectionRatio > 0 });
      if (res.intersectionRatio > 0) {
        console.log('元素可见');
      } else {
        console.log('元素不可见');
      }
    });
    this.data.observer = observer;
  },
  onUnload() {
    if (this.data.observer) {
      this.data.observer.disconnect();
    }
  },
});
```

```css
// index.tyss
.container {
  height: 100vh;
}
.placeholder {
  height: 800rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
.target {
  height: 300rpx;
  background-color: #e8f4ff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.status {
  position: fixed;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(0,0,0,0.6);
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}
```
