uniapp中获取元素页面信息的方法

uni.createSelectorQuery()返回一个 SelectorQuery 对象实例。可以在这个实例上使用 select 等方法选择节点,并使用 boundingClientRect 等方法选择需要查询的信息。
需要注意的是:
使用 uni.createSelectorQuery() 需要在生命周期 mounted 后进行调用。

一,selectorQuery.select(selector)

在当前页面下选择第一个匹配选择器 selector 的节点,返回一个 NodesRef 对象实例,可以用于获取节点信息
selector 类似于 CSS 的选择器,但仅支持下列语法。

ID选择器:#the-id
class选择器(可以连续指定多个):.a-class.another-class
子元素选择器:.the-parent > .the-child
后代选择器:.the-ancestor .the-descendant
跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant
多选择器的并集:#a-node, .some-other-nodes

二,selectorQuery.selectAll(selector)

在当前页面下选择匹配选择器 selector 的所有节点,返回一个 NodesRef 对象实例,可以用于获取节点信息。

ID选择器:#the-id
class选择器(可以连续指定多个):.a-class.another-class
子元素选择器:.the-parent > .the-child
后代选择器:.the-ancestor .the-descendant
跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant
多选择器的并集:#a-node, .some-other-nodes

三,nodesRef.boundingClientRect(callback)

添加节点的布局位置的查询请求。相对于显示区域,以像素为单位。其功能类似于 DOM 的 getBoundingClientRect。返回 NodesRef 对应的 SelectorQuery
在这里插入图片描述
返回的节点信息中,每个节点的位置用 left、right、top、bottom、width、height 字段描述。如果提供了 callback 回调函数,在执行 selectQuery 的 exec 方法后,节点信息会在 callback 中返回。

四,selectorQuery.in(component)

将选择器的选取范围更改为自定义组件 component 内,返回一个 SelectorQuery 对象实例。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。

<template>
	<view class="content">
		<view class="box">
			文字
		</view>
		<view class="box" >
			文字
		</view>
		<view class="box">
			文字
		</view>
	</view>
</template>

<script>
	export default {
		onReady() {  //需要注意的是放在onload中是不行的
			const query = uni.createSelectorQuery().in(this);     //这样写就只会选择本页面组件的类名box的
			query.selectAll('.box').boundingClientRect(data => {   //回调函数,data中存储的是这些元素节点(每个节点的信息存为一个对象)的位置信息
			  console.log("得到布局位置信息" + JSON.stringify(data));
			  console.log("节点离页面顶部的距离为" + data[1].top);  //本页面共有三个,这里我只打印第二个的
			}).exec();
		}
	}
</script>

<style>
	.content {

	}
	.box{
		width: 100rpx;
		height: 100rpx;
		background-color: green;
	}
</style>

在这里插入图片描述

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值