在uniapp开发中,需要获取到dom的信息,需要用到uniapp的指定方式
uni.createSelectorQuery(),但是每次需要用到的时候都需要很长一段的繁琐代码,本篇文章将呈现获取dom信息方法封装,话不多说,上菜:
getDomInfo(id, that) {return new Promise((resolve, reject) => {if (!id) return reject('id/类名 不能为空')if (!that) return reject('this指向不能为空')const query = uni.createSelectorQuery().in(that);query.select(id).boundingClientRect(data => {// console.log("节点离页面顶部的距离为" + data.height);resolve(data || {})}).exec();})
},
因为uni.createSelectorQuery()是一个异步方法,所以封装的时候将其封装在一个Promise里面,其方法需要传入两个参数(元素id/类名,当前页面的this),下面举例使用:
<template><view class="page"><view class="dom"></view></view>
</template><script>
export default {async mounted() {let domInfo = await this.$util.getDomInfo('.dom', this);},
}
</script><style lang="scss" scoped>
.dom{width: 250rpx;height: 500rpx;
}
</style>
注:该方法需要早mounted挂载后使用才行,要不无法获取到dom信息