在需要判断是否到达顶部的元素前面放置一个dom元素
<view id="sentinel" style="height: 1px; width: 100%;"></view>
data() {
return {
isStuck: false
};
},
onReady() {
const sysInfo = uni.getSystemInfoSync()
const navH = sysInfo.statusBarHeight + 44
this.navHeight = navH + 'px'
this.$nextTick(() => {
this.setupObserver(navH);
});
}, //先获取导航栏的高度
methods: {
setupObserver(navH) {
// 创建交叉观察器
this._observer = uni.createIntersectionObserver(this);
// relativeToViewport({ top: -navH }) 的意思是:
// 将视图的上方边界往下缩小 navH 个像素(刚好是导航栏的底部边缘)
this._observer.relativeToViewport({ top: -navH }).observe('#sentinel', (res) => {
console.log(res,'1111111111')
// intersectionRatio === 0 表示哨兵元素已经完全离开了我们划定的视图区域
// res.boundingClientRect.top < navH 确保是从上面离开的(也就是滚上去了),而不是还没滚出来
if (res.intersectionRatio === 0 && res.boundingClientRect.top < navH) {
console.log('吸顶了')
this.isStuck = true; // 吸顶了,显示标题
} else {
console.log('没有没有')
this.isStuck = false; // 还没吸顶,隐藏标题
}
});
}
}