微信小程序判斷頁面滑動方向
微信小程序在開發(fā)過程中,我們可能會需要判斷小程序頁面滾動方向是向上,還是向下,那么該如何判斷呢,下面小編為大家解答。
微信小程序判斷頁面滑動方向
解決方案
1.用到微信小程序API
獲取頁面實際高度 nodesRef.boundingClientRect([callback])
監(jiān)聽用戶滑動頁面事件onPageScroll。
2.獲取頁面實際高度
<!--WXML-->
<view id="box">
<view class="list" wx:for="{{List}}" wx:key="List{{index}}">
<image mode='aspectFill' class='list_img' src="{{item.imgUrl}}" ></image>
</view>
</view>
/* JS */ // 封裝函數(shù)獲取ID為box的元素實際高度 getScrollHeight: function() { wx.createSelectorQuery().select('#box').boundingClientRect((rect) => { this.setData({ scrollHeight: rect.height }) console.log(this.data.scrollHeight) }).exec() }, // 假設(shè)數(shù)據(jù)請求 getDataList: function() { wx.request({ url: 'test.php', //僅為示例,并非真實的接口地址 success: function(res) { // 如果該元素下面的數(shù)據(jù)是動態(tài)獲取的,此方法在wx.request請求成功的回調(diào)函數(shù)中調(diào)用 this.getScrollHeight() } }) },
3.監(jiān)聽用戶滑動頁面事件
//監(jiān)聽用戶滑動頁面事件
onPageScroll: function(e) {
if (e.scrollTop <= 0) {
// 滾動到最頂部
e.scrollTop = 0;
} else if (e.scrollTop > this.data.scrollHeight) {
// 滾動到最底部
e.scrollTop = this.data.scrollHeight;
}
if (e.scrollTop > this.data.scrollTop || e.scrollTop >= this.data.scrollHeight) {
//向下滾動
console.log('向下 ', this.data.scrollHeight)
} else {
//向上滾動
console.log('向上滾動 ', this.data.scrollHeight)
}
//給scrollTop重新賦值
this.setData({
scrollTop: e.scrollTop
})
},


立即掃碼關(guān)注

多門店/直營/加盟連鎖管理系統(tǒng)