创建并返回一个 IntersectionObserver 对象实例。在自定义组件或包含自定义组件的页面中,应使用 this.createIntersectionObserver(options) 来代替。
Object component 自定义组件实例
Object options 选项
属性 | 类型 | 默认值 | 必填 | 说明 | 最低版本 |
---|---|---|---|---|---|
thresholds | Array. | 0 | 否 | 一个数值数组,包含所有阈值 | |
initialRatio | number | 0 | 否 | 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数 | |
selectAll | boolean | false | 否 | 是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) 2.0.0 |
IntersectionObserver
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(); } });
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(); } });