小程序开放平台

文档中心
基础
路由
跳转
转发
界面
网络
支付
数据缓存
媒体
位置
开放接口
设备
XHSML
createIntersectionObserver
intersectionObserver
createSelectorQuery
SelectorQuery
nodeRef
性能
第三方平台
文件
数据分析
画布

xhs.createIntersectionObserver

开发
>
JS API
>
XHSML
>
createIntersectionObserver
>
更新时间:2024-11-13 19:05:31

创建并返回一个 IntersectionObserver 对象实例。在自定义组件或包含自定义组件的页面中,应使用 this.createIntersectionObserver(options) 来代替。

参数

Object component 自定义组件实例

Object options 选项

options

属性
类型
默认值
必填
说明
最低版本
thresholdsArray.0一个数值数组,包含所有阈值
initialRationumber0初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数
selectAllbooleanfalse是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) 2.0.0

返回值

IntersectionObserver

示例代码

javascript
  Page({
    data: {
      appear: false
    },
    onLoad() {
      this.intersectionObserver = xhs.createIntersectionObserver(this);
      // 监测 scroll-view 可视区域和小球元素节点的相交情况
      console.log('xhs.createIntersectionObserve的可选值', this.intersectionObserver._options);
      this.intersectionObserver
        .relativeTo('.scroll-view')
        .observe('.ball', res => {
        console.log('observe', res);
        // boundingClientRect: 目标边界,这里指小球的位置情况,这个位置是相对于整个页面的,不是相对于参照元素的 scroll-view 的
        // dataset: 观察对象携带的数据。
        // id: 观察对象的 id,它与上面的 dataset 多使用于一次观察多个对象的场景,用于区分不同的对象。
        // intersectionRatio: 相交比例,为 0 时说明两者不相交。
        // intersectionRect: 相交区域,height 为 0 时说明此时没有相交。
        // relativeRect: 参照区域的边界,作为参考物,它的值一般是不会变的。可以对比它于开始相交时一直没变,因为它就是一个 scroll-view 的组件在页面上呈现出的位置信息。
        // time: 监测到两者相交时的时间戳
        this.setData('appear', res.intersectionRatio > 0);
      });
    },
    onUnload() {
      this.intersectionObserver && this.intersectionObserver.disconnect();
    }
  });

selectAll

javascript
  Page({
    data: {
        appear: false
    },
    onReady() {
        this.intersectionObserver = xhs.createIntersectionObserver(this, {
          selectAll: true
        });
        this.intersectionObserver
          .relativeTo('.scroll-view')
          .observe('.ball, .ball2', res => {
            console.log('observe', res)
            this.setData('appear', res.intersectionRatio > 0);
        });
    },
    onUnload() {
        this.intersectionObserver && this.intersectionObserver.disconnect();
    }
  });
该文档是否对您有帮助?