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节点,来发起请求的操作了,因为我的页面有多个数据,和特殊的请求判断,所以在内部进行了一些逻辑处理,你们可以根据自己的需求进行代码书写