Article directory
Get node information
createSelectorQuery
wx.createSelectorQuery()
It can be used to obtain information such as node attributes, styles, and positions on the interface.
The most common usage is to use this interface to query the current position of a node and the scrolling position of the interface.
Sample code:
const query = wx.createSelectorQuery()
query.select('#the-id').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function(res){
res[0].top // #the-id节点的上边界坐标
res[1].scrollTop // 显示区域的竖直滚动位置
})
In custom components or pages containing custom components, use this.createSelectorQuery
instead wx.createSelectorQuery
to ensure that nodes are selected in the correct range.
selectViewport
selectViewport()
Can be used to scroll-view
get the size, scroll position and other information
*注意:selectViewport()没有参数的
选择显示区域。可用于获取显示区域的尺寸、滚动位置等信息
onLoad: function (options) {
const query=wx.createSelectorQuery(); //创建一个SelectorQuery 对象实例
query.selectViewport(). //选择显示区域
scrollOffset(function(res){
//查询节点(必须是scroll-view / viewport)的滚动位置
res.id // 节点的ID
res.dataset // 节点的dataset
res.scrollLeft // 节点的水平滚动位置
res.scrollTop // 节点的竖直滚动位置
}).exec()
}
boundingClientRect
Add a query request for the layout position of the node. Relative to the display area, in pixels.
After executing SelectorQuery.exec
the method , node information will be callback
returned in .
Sample code:
Page({
getRect () {
wx.createSelectorQuery().select('#the-id').boundingClientRect(function(rect){
rect.id // 节点的ID
rect.dataset // 节点的dataset
rect.left // 节点的左边界坐标
rect.right // 节点的右边界坐标
rect.top // 节点的上边界坐标
rect.bottom // 节点的下边界坐标
rect.width // 节点的宽度
rect.height // 节点的高度
}).exec()
},
getAllRects () {
wx.createSelectorQuery().selectAll('.a-class').boundingClientRect(function(rects){
rects.forEach(function(rect){
rect.id // 节点的ID
rect.dataset // 节点的dataset
rect.left // 节点的左边界坐标
rect.right // 节点的右边界坐标
rect.top // 节点的上边界坐标
rect.bottom // 节点的下边界坐标
rect.width // 节点的宽度
rect.height // 节点的高度
})
}).exec()
}
})
fields
Get information about a node. The fields to be retrieved are specified fields
in .
Sample code:
Page({
getFields () {
wx.createSelectorQuery().select('#the-id').fields({
dataset: true,
size: true,
scrollOffset: true,
properties: ['scrollX', 'scrollY'],
computedStyle: ['margin', 'backgroundColor'],
context: true,
}, function (res) {
res.dataset // 节点的dataset
res.width // 节点的宽度
res.height // 节点的高度
res.scrollLeft // 节点的水平滚动位置
res.scrollTop // 节点的竖直滚动位置
res.scrollX // 节点 scroll-x 属性的当前值
res.scrollY // 节点 scroll-y 属性的当前值
// 此处返回指定要返回的样式名
res.margin
res.backgroundColor
res.context // 节点对应的 Context 对象
}).exec()
}
})