后浪云百度小程序教程:swan.createIntersectionObserver
- swan.createIntersectionObserver
- 方法参数
- options 参数说明
- 示例
- 代码示例 1
- 代码示例 2:options 为 thresholds 时
- 代码示例 3:options 为 initialRatio 时
- 代码示例 4:options 为 selectAll 时
- 方法参数
swan.createIntersectionObserver
解释: 创建并返回一个 IntersectionObserver 对象实例。在自定义组件中,可以使用 this.createIntersectionObserver([options]) 来代替。
方法参数
Object object
options 参数说明
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
thresholds | Array | 否 | [0] | 一个数值数组,包含所有阈值 |
initialRatio | number | 否 | 0 | 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数 |
selectAll | Boolean | 否 | false | 是否同时观测多个目标节点(而非一个),如果设为 true ,observe 的 targetSelector 将选中多个节点(注意:同时选中过多节点将影响渲染性能) |
示例
扫码体验
代码示例

请使用百度APP扫码
代码示例 1
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
- SWAN
- JS
- CSS
<view class="wrap"><view class="message"><text s-if="appear">小球出现</text><text s-else>小球消失</text></view><scroll-view class="scroll-view" scroll-y><view class="scroll-area" style="{{appear ? 'background: #ccc' : ''}}"><text class="notice">向下滚动让小球出现</text><view class="filling"></view><view class="ball"></view></view></scroll-view></view>
代码示例 2:options 为 thresholds 时
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
- JS
Page({data: {appear: false},onReady() {this.intersectionObserver = swan.createIntersectionObserver(this, {// 阈值数量设置少,避免触发过于频繁导致性能问题// 通常会设置为 1,表示元素要完全展示在页面上才会进行记录thresholds: [0, 0.5, 1]});// 监测 scroll-view 可视区域和小球元素节点的相交情况// 配置 thresholds:[1],那么当监听对象和参照物相交比例达到 1 时,会触发监听器的回调函数console.log('监听实例', this.intersectionObserver);this.intersectionObserver.relativeTo('.scroll-view').observe('.ball', res => {console.log('observe', res);// intersectionRatio: 相交比例,为 0 时说明两者不相交。this.setData('appear', res.intersectionRatio > 0);});},onUnload() {this.intersectionObserver && this.intersectionObserver.disconnect();}});
代码示例 3:options 为 initialRatio 时
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
- JS
Page({data: {appear: false},onReady() {this.intersectionObserver = swan.createIntersectionObserver(this, {// 初始相交比例,默认 0,达到 initialRatio 或 thresholds 中的阈值时,回调被触发initialRatio: 1});// 监测scroll-view可视区域 和 小球元素节点的相交情况// 配置了 thresholds:[1],那么当监听对象和参照物相交比例达到 1 时,会触发监听器的回调函数this.intersectionObserver.relativeTo('.scroll-view').observe('.ball', res => {console.log('observe', res);// intersectionRatio: 相交比例,这里为 0 时说明两者不相交。this.setData('appear', res.intersectionRatio > 0);});},onUnload() {this.intersectionObserver && this.intersectionObserver.disconnect();}});
代码示例 4:options 为 selectAll 时
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
- JS
Page({data: {appear: false},onReady() {this.intersectionObserver = swan.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();}});
版权声明:
作者:后浪云
链接:https://idc.net/help/186671/
文章版权归作者所有,未经允许请勿转载。
THE END
