uniapp监听当前元素是否出现在页面

uniapp开发小程序或app,有一些dom节点的抓取兼容问题,比如你并不能使用document.getByElementId等方法获取到页面上的dom节点,需要通过uni.createSelectorQuery()方法来获取到,并且要通过in(this)来声明它获取的位置,如下可获取到当前页面的节点

const query = uni.createSelectorQuery().in(this);

这是我实现的代码,可以参考,增加定时器是为了稳定性,uni获取节点时,有一定的延时性

let arr = []
				const {
					windowHeight
				} = uni.getSystemInfoSync()
				setTimeout(() => {
					if (this.isValidArray(this.activeContents) && this.activeContents.length > 0) {
						for (let i = 0; i < this.activeContents.length; i++) {
							if (this.activeContents[i].type == 2) {
								arr.push(this.activeContents[i])
							}
						}
						for (let j = 0; j < arr.length; j++) {
							//根据最初值,给一个完成状态
							if (arr[j].executed) {
								arr[j].judge = true
							} else {
								arr[j].judeg = false
							}
							let task = '.text' + arr[j].eId
							const query = uni.createSelectorQuery().in(this);
							// 选择节点
							query.select(task).boundingClientRect(data => {
								const {
									top,
									height
								} = data
								if ((top < windowHeight) && (top + height > 0)) {
									//如果已经完成了,不操作
									if (arr[j].judge) {

									} else {
										let params = {
											classId: 0,
											contentKey: arr[j].key,
											dsId: this.id,
											taskid: this.gId,
											isTeach: false
										}
										if (this.account && this.session) { //登录状态下
											this.$api.exectionWord(params).then(res => {
												//因为不请求接口,所以完成后本地赋值为true
												arr[j].judge = true
												this.noLoadingGet()
											})
										} else { //未登录预览
											arr[j].judge = true
										}
									}
									// console.log('元素在可视区域出现')
								} else {
									// console.log('元素在不可视区域出现')
								}
							}).exec()
						}
					}
				}, 500)

这就是一个判断当前页面是否出现该dom节点,来发起请求的操作了,因为我的页面有多个数据,和特殊的请求判断,所以在内部进行了一些逻辑处理,你们可以根据自己的需求进行代码书写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值