最近在做一個ipad端的下拉框組件,功能實現並不復雜,難的是如何判斷當下拉框超出可視范圍時的狀態,
當時查了好多資料得出的結論是:
let view = uni.createSelectorQuery().in(this).select('class') view.fields({ size: true,//是否返回節點尺寸(width
height
) rect: true,//是否返回節點的scrollLeft
scrollTop
,節點必須是scroll-view
或者viewport
scrollOffset: true,//是否返回節點的scrollLeft
scrollTop
,節點必須是scroll-view
或者viewport
}, (res) => { if (res.bottom > 500) { let up = this.list.length > 6 ? 6 : this.list.length up *= 80 up += 10 this.topShowStyle = 'top:-'+up+'upx;' } }).exec();
可能很多同學都認識:uni.createSelectorQuery().select('class'),但是:uni.createSelectorQuery().in(this).select('class')這個會被忽略掉,
兩者之間的區別:
uni.createSelectorQuery().select('class'):(組件情況下,非組件下沒試過)返回當前節點相對於該節點父元素的位置信息,就是說返回的數據left丶right丶bottom丶top都是相對於父元素的距離,並不是我們想要的相對於頁面的位置
所以正確的方法得加上.in(this)
uni.createSelectorQuery().in(this)官方文檔給出的解釋是:將選擇器的選取范圍更改為自定義組件 component
內,返回一個 SelectorQuery
對象實例。(初始時,選擇器僅選取頁面范圍的節點,不會選取任何自定義組件中的節點)。
因為我做的是組件,所以用uni.createSelectorQuery().select('class')得到的節點是相對於父元素節點的位置,要獲取組件相對於頁面的位置應該用uni.createSelectorQuery().in(this).select('class')
想查看更多節點信息的同學可以去官網查看文檔:https://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery