微信小程序 IntersectionObserver 用法详解

<view class="container">
  <view class="page-body">
    <view class="page-section message">
      <text wx:if="{{appear}}">
        小球出现
      </text>
      <text wx:else>
        小球消失
      </text>
    </view>
    <view class="page-section">
      <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>
  </view>
</view>
.scroll-view {
  height: 400rpx;
  background: #fff;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.scroll-area {
  height: 1300rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: .5s;
}

.notice {
  margin-top: 150rpx;
}

.ball {
  width: 200rpx;
  height: 200rpx;
  background: #1AAD19;
  border-radius: 50%;
}

.filling {
  height: 400rpx;
}

.message {
  width: 100%;
  display: flex;
  justify-content: center;
}

.message text {
  font-size: 40rpx;
  font-family: -apple-system-font, Helvetica Neue,Helvetica,sans-serif;
}
Page({
  data: {
    appear: false
  },
  onLoad() {
    this._observer = wx.createIntersectionObserver(this)
    this._observer
      .relativeTo('.scroll-view')
      .observe('.ball', (res) => {
        console.log(res);
        this.setData({
          appear: res.intersectionRatio > 0
        })
      })
  },
  onUnload() {
    if (this._observer) this._observer.disconnect()
  }
})

1,boundingClientRect:目标边界。这个目标,就是我们的观察对象,可以看到刚开始相交的时候,它的位置情况。这个位置是相对于整个页面的,不是相对于参照元素的。top = 251(px) = scroll-view的高度(200px) + "小球消失/出现"message的高度(52px) - 相交高度(1px)
2,dataset: 观察对象携带的数据。
3,id:观察对象的id,它与上面的dataset多使用于一次观察多个对象的场景,用于区分不同的对象。
4,intersectionRatio 相交比例:大于0的话表示两者有了交集,等于1的话表示两者已经完全相交。
5,intersectionRect 相交区域: 可以看出此时只有1px的高度有交集。
6,relativeRect:参照区域的边界。通过其上下左右四个属性值可以看出它就是scroll-view组件在页面中的位置。
7,time: 监测到两者相交时的时间戳,不太有用。

参考地址:https://blog.csdn.net/qq_25324335/article/details/83687695

原文地址:https://www.cnblogs.com/Webzhoushifa/p/12746418.html