Detailed usage of WeChat Mini Program 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 : target boundary. This goal, which is our observation object, can see its position when it first starts to intersect. This position is relative to the entire page, not to the reference element. top = 251 (px) = height of scroll-view (200px) + height of "small ball disappears / appears" message (52px)-intersection height (1px)
2, dataset : data carried by the observation object.
3, id : the id of the observation object, which is used in the scene of observing multiple objects at once with the above dataset to distinguish different objects.
4. intersectionRatio : If it is greater than 0, it means that the two have an intersection. If it is 1, it means that the two have completely crossed.
5. intersectionRect intersection area: It can be seen that only 1px height has intersection at this time.
6, relativeRect : Reference area boundary. It can be seen from the four attribute values ​​of up, down, left, and right that it is the position of the scroll-view component on the page.
7. time : The timestamp when the two intersect is detected, which is not very useful.

Reference address: https://blog.csdn.net/qq_25324335/article/details/83687695

Guess you like

Origin www.cnblogs.com/Webzhoushifa/p/12746418.html