![b620ed54759dba92f5643e96fa5292e0.png](https://img-blog.csdnimg.cn/img_convert/b620ed54759dba92f5643e96fa5292e0.png)
通过微信小程序官方api我们不难找到SelectorQuery可以满足我们的需求,官方给我们的例子如下
//以下代码获取到的是组件中id="the-id"的DOM元素Component({ queryMultipleNodes() { const query = wx.createSelectorQuery().in(this) query.select('#the-id').boundingClientRect(function (res) { res.top // 这个组件内 #the-id 节点的上边界坐标 }).exec() }})
注意:使用以上代码获取组件DOM的条件时该组件已经渲染在页面上,否则获取不到DOM对象。
我们构建如下代码来加以说明(关于自定义组件的相关知识这里就不展开说明,有需要了解的自行浏览官方文档):
页面代码
以下内容为组件内容
页面json代码
{ "usingComponents": { "modal":"/components/modal/modal" }}
组件代码
自定义组件(弹窗) 内容填充,测试该view的高度
组件js代码
// components/modal/modal.jsComponent({ created: function () { console.log("Component is created") }, ready: function () { const query = wx.createSelectorQuery().in(this) query.select('#test-view').boundingClientRect(function (res) { console.log("test-view"+res) }).exec() },})
我们设置四组对照,对照参数与结果见下表
![9c25da9b088db94b0455589e30dd197e.png](https://img-blog.csdnimg.cn/img_convert/9c25da9b088db94b0455589e30dd197e.png)
由此我们可以看到只有当showModal=true show=true即组件内容在页面中渲染时才能获取到组件的DOM元素。