節點信息查詢 API 可以用於獲取節點屬性、樣式、在界面上的位置等信息。
最常見的用法是使用這個接口來查詢某個節點的當前位置,以及界面的滾動位置。
示例代碼:
const query = wx.createSelectorQuery() query.select('#the-id').boundingClientRect(function(res){ res.top // #the-id 節點的上邊界坐標(相對於顯示區域) }) query.selectViewport().scrollOffset(function(res){ res.scrollTop // 顯示區域的豎直滾動位置 }) query.exec()
上述示例中, #the-id
是一個節點選擇器,與 CSS 的選擇器相近但略有區別,請參見 SelectorQuery.select 的相關說明。
在自定義組件或包含自定義組件的頁面中,推薦使用 this.createSelectorQuery
來代替 wx.createSelectorQuery ,這樣可以確保在正確的范圍內選擇節點
將選擇器的選取范圍更改為自定義組件 component
內。(初始時,選擇器僅選取頁面范圍的節點,不會選取任何自定義組件中的節點)。
注:在小程序組件的ready生命周期中進行調用,即可獲取節點信息。
Component({ methods: { queryMultipleNodes (){ const query = wx.createSelectorQuery().in(this) query.select('#the-id').boundingClientRect(function(res){ res.top // 這個組件內 #the-id 節點的上邊界坐標 }).exec() } }, lifetimes: { attached: function () { // 在組件實例進入頁面節點樹時執行 }, detached: function () { // 在組件實例被從頁面節點樹移除時執行 }, ready: function(){ console.log('ready'); this.queryMultipleNodes ();// 獲取節點信息 } }, })
參考:
獲取節點信息:
https://developers.weixin.qq.com/miniprogram/dev/framework/view/selector.html
組件中獲取節點信息:
https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.in.html
組件生命周期:
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html