外观
getClientRect 获取元素位置与尺寸
约 369 字大约 1 分钟
2024-01-01
介绍
基于 uni.createSelectorQuery() 查询节点的布局信息,getClientRect 查询单个节点,getClientRectAll 查询所有匹配节点,均返回 Promise。
基本用法
import { getClientRect, getClientRectAll } from '@/uni_modules/uview-unix'
// 查询单个节点
const info = await getClientRect('#target')
console.log(info.width, info.height, info.left, info.top)
// 在组件作用域内查询,避免样式/选择器冲突
const child = await getClientRect('.item', this)
// 批量查询
const list = await getClientRectAll('.list-item')
list.forEach((item) => console.log(item.width, item.height))getClientRect(selector: string, component?: any | null, fields?: NodeField | null): Promise<NodeInfo>
查询第一个匹配节点的布局信息。
参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| selector | CSS 选择器,如 #id、.class | string | - |
| component | 组件实例,传入后在该组件作用域内查询 | any | null | null |
| fields | 查询字段配置,默认查询 size 与 rect | NodeField | null | null |
返回值
Promise<NodeInfo>:匹配到节点时返回节点信息对象,未匹配时返回空对象 {}。默认字段下包含 width、height(size)以及 left、top、right、bottom(rect)。
getClientRectAll(selector: string, component?: any | null, fields?: NodeField | null): Promise<NodeInfo[]>
查询所有匹配节点的布局信息,参数含义与 getClientRect 相同。
返回值
Promise<NodeInfo[]>:匹配到节点时返回节点信息数组,未匹配时返回空数组 []。
注意事项
- 需要在节点完成渲染后调用,否则可能查不到节点而得到空结果。
- 查询字段通过
fields自定义时,返回对象只包含所查询的字段。
