微信官方文档 wx.createSelectorQuery()
官方代码如下:
const query = wx.createSelectorQuery()
query.select('#the-id').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function (res) {
res[0].top // #the-id节点的上边界坐标
res[1].scrollTop // 显示区域的竖直滚动位置
})
console.log(res)输出res结果,在控制台看到以下的结果
可以看到res返回一个包含两个对象的数组,第一个对象包含元素的基本属性(width、height、top、left、right、bottom),第二个对象包含元素滚动属性(scrollLeft、scrollTop)
如果常用第一个对象的属性,可以进行封装,代码如下:
queryNodeAttr (id, attr, data) {
let query = wx.createSelectorQuery();
query.select(id).boundingClientRect();
query.selectViewport().scrollOffset()
query.exec((res) => {
this.setData({
[data]: res[0][attr]
});
});
},
在使用时调用:
// .wxml
<view id="comments"></view>
// .js
this.queryNodeAttr('#comments', 'top', 'commentsTop');
注意id值前面需要加上#