最近有個需求需要實現(xiàn)獲取小程序的滾動停止的位置逗扒,并觸發(fā)事件塔拳。
不能使用touchstart和touchend,因為這些是觸摸事件涛目,觸摸事件完成后頁面仍然會繼續(xù)滑動秸谢。
查詢微信小程序官方文檔得知经磅,有個滑動事件:
image.png
在page對象里加入下面代碼,即可獲取頁面滾動的位置钮追。
onPageScroll(res){
console.log(res.scrollTop);
this. getScrollTop(res.scrollTop)
},
由于只要在滾動中预厌,就會不停地觸發(fā)這個事件,而我們只需要獲取它停下來時的位置元媚,因此還需要下面的小技巧轧叽,使用setTimeOut延時執(zhí)行滑動停止的代碼:
let scrollTopTimeOut;
getScrollTop(scrollTop){
clearTimeout(scrollTopTimeOut);
scrollTopTimeOut = setTimeout(() =>{
// 滑動停止的代碼,此處半秒內(nèi)位置不變即為滑動停止刊棕。
}, 500);
}
獲取某元素位置:
const query = wx.createSelectorQuery().in(this)
setTimeout(() => {
query.select('#elementId).boundingClientRect((rect) =>{
this.setData({
position: rect.top
})
}).exec();
}, 1000)
提醒:在自定義組件內(nèi)獲取必須用wx.createSelectorQuery().in(this)炭晒,在onReady內(nèi)加入以上代碼還必須加上setTimeOut延時獲取,否則boundingClientRect獲取到的rect值為null甥角。