外观
getClientRect 获取元素位置与尺寸
约 310 字大约 1 分钟
2024-01-01
介绍
提供获取元素位置和尺寸信息的工具函数,基于 uni-app 的 SelectorQuery API。
getClientRect(selector: string, component?: any): Promise
获取指定选择器的元素的位置和尺寸信息。
- 参数
- selector: CSS 选择器
- component: 组件实例,默认不传入
- 返回值
<Promise>Promise 对象,resolve 的结果是元素的位置和尺寸信息
getClientRectAll(selector: string, component?: any): Promise
获取所有匹配选择器的元素的位置和尺寸信息。
- 参数
- selector: CSS 选择器
- component: 组件实例,默认不传入
- 返回值
<Promise>Promise 对象,resolve 的结果是元素位置和尺寸信息的数组
示例代码
<template>
<view>
<view id="testElement" style="width: 300rpx; height: 200rpx; background-color: #007AFF; color: white; display: flex; align-items: center; justify-content: center; margin-bottom: 40rpx;">目标元素</view>
<button @click="getElementInfo">获取元素信息</button>
<view v-if="elementInfo">
<text>元素位置和尺寸信息:</text>
<text>left: {{ elementInfo.left }}</text>
<text>top: {{ elementInfo.top }}</text>
<text>width: {{ elementInfo.width }}</text>
<text>height: {{ elementInfo.height }}</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import { getClientRect } from '@/uni_modules/uview-unix'
const elementInfo = ref<any>(null)
const getElementInfo = async () => {
try {
// 获取元素信息
const info = await getClientRect('#testElement')
elementInfo.value = info
console.log('元素信息:', info)
} catch (error) {
console.error('获取元素信息失败:', error)
}
}
</script>