scrollHandle(e) { let view = uni.createSelectorQuery().in(this).selectAll('.list-item'); view .boundingClientRect((d) => { let top = d[0].top; d.forEach((item) => { item.top = item.top - top; item.bottom = item.bottom - top; this.letterDetails.push({ id: item.id, top: item.top, bottom: item.bottom, }); }); }) .exec(); const scrollTop = e.detail.scrollTop; this.letterDetails.some((item) => { if (scrollTop >= item.top && scrollTop <= item.bottom - 20) { this.currentLetter = item.id; //当前固定用的是粘性定位,如果不用粘性定位,在这里设置 return true; } }); },
时间: 2024-03-03 11:52:14 浏览: 18
这段代码是一个滚动事件处理函数,传入一个事件对象e,在函数内部获取了所有class为'list-item'的元素的位置信息,并存储到this.letterDetails数组中。然后,获取滚动条的位置scrollTop,遍历this.letterDetails数组,找到第一个top小于等于scrollTop且bottom-20大于scrollTop的元素,将该元素的id赋值给this.currentLetter,并返回true结束循环。该函数的作用是根据滚动条的位置,找到当前应该固定显示的元素,并更新this.currentLetter的值。
相关问题
onReady() { let view = uni.createSelectorQuery().select(".homedata"); view.boundingClientRect(data => { console.log(data); // this.clentHeight = data.height; }).exec(); },为什么data为null
在你提供的代码中,可以看到你使用了 `uni.createSelectorQuery()` 方法来创建一个选择器查询实例,并使用 `select()` 方法选择了一个类名为 "homedata" 的元素。
根据你的描述,当执行 `boundingClientRect()` 方法时,`data` 参数返回了 null。这可能是因为选择器查询实例还没有执行 `exec()` 方法来触发查询操作。
`uni.createSelectorQuery()` 方法返回的是一个选择器查询实例,你需要调用 `exec()` 方法来执行查询操作并获取结果。在你的代码中,你需要将 `.exec()` 方法链式调用到 `select()` 方法之后,如下所示:
```javascript
onReady() {
uni.createSelectorQuery().select(".homedata").boundingClientRect(data => {
console.log(data);
// this.clentHeight = data.height;
}).exec();
}
```
确保在调用 `boundingClientRect()` 方法之前,先调用了 `exec()` 方法来触发查询操作。这样应该能够正确获取到元素的 boundingClientRect 数据。如果仍然返回 null,请检查选择器是否正确,元素是否已加载和渲染完成。
uni.createSelectorQuery()使用方法
uni.createSelectorQuery()是用来获取页面上的节点信息的API,可以用来获取节点的位置、尺寸、样式等信息。具体使用方法如下:
1. 在页面的onLoad生命周期函数中,创建一个selectorQuery对象:
```
let query = uni.createSelectorQuery()
```
2. 使用selectorQuery对象的方法来选择需要获取信息的节点,例如:
```
query.select('#my-node').boundingClientRect()
```
其中,#my-node是需要获取信息的节点的id,boundingClientRect()是获取节点的位置、尺寸等信息的方法。
3. 使用exec()方法来执行获取信息的操作,并在回调函数中处理获取到的信息:
```
query.exec(function(res) {
console.log(res[0].width) // 获取节点的宽度
})
```
其中,res是一个数组,每个元素对应一个之前选择的节点,数组中的每个元素都包含了该节点的位置、尺寸、样式等信息。
完整示例代码如下:
```
export default {
onLoad() {
let query = uni.createSelectorQuery()
query.select('#my-node').boundingClientRect()
query.exec(function(res) {
console.log(res[0].width) // 获取节点的宽度
})
}
}
```