在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信息