uni .createSelectorQuery() .in(this) .select(".container .cat-box") .boundingClientRect((data) => { this.pageScroll = data.top; }) .exec();
data回調參數包括了組件的一些信息,包括距離頭部的距離
使用這個方法獲取距離時 有兩個條件:
1、在onReady或者mounted中使用;
2、保證前面的圖片高度設置好了,因為uni-image有個默認高度為 height: 240px ,容易造成偏差;
3、正常情況下this指的應該是該方法mounted或onReady所在的vue元素,然而在wx小程序中,輸出的this並未指向這個vue元素,即el為none,那么問題來了,this.pageScroll = data.top; 將無法獲取想要的信息,解決方法:
const that = this uni .createSelectorQuery() .in(this) .select(".container .cat-box") .boundingClientRect((data) => { that.pageScroll = data.top; }) .exec();