微信小程序 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM