1.前提概要
当目标元素超出基准元素时,头部元素吸顶,如图所示:
其中B元素为固定在底部的元素
2.思路讲解
- 获取A元素和B元素初始离顶部的距离
- 获取滚动的距离
- 其中要明白的是滚动的距离就是A元素上升的距离,则当A元素初始距离减去上升距离小于B元素的初始距离时,则表示A元素已经超出B元素,此时C元素显示
3.代码演示
主要方法: 对于节点的获取:
- uni.createSelectorQuery()=>得到seletorQuery对象实例
- selectorQuery.in(this)=>表示选择器的取值范围为当前组件内=>仍旧返回selectQuery对象
- selectorQuery.select('选择器')=>表示匹配对应选择器节点,返回一个NodesRef对象实例
- nodesRef.boundingClientRect(callback)=>添加节点的布局位置查询请求,返回NodesRef对应的selectorQuery对象
- selectorQuery.exec()=>执行所有请求
//初始距离获取--注意只能在mounted之后获取初始距离
mounted() {
const query = uni.createSelectorQuery().in(this);
query.select('#A').boundingClientRect(data=>{
console.log('得到布局位置信息',JSON.stringify(data));
console.log('节点离页面顶部的距离为',data.top);
this.myScroll = data.top;
}).exec();
const query1 = uni.createSelectorQuery().in(this);
query1.select("#B").boundingClientRect(data=>{
console.log('底部信息',JSON.stringify(data));
console.log('底部top',data.top);
this.myBottom = data.top;
}).exec();
},
//滚动距离获取
onPageScroll(e) {
if( this.myScroll - e.scrollTop < this.myBottom) {
this.show = true;//控制C元素显示的值
} else {
this.show = false;
}
}
参考链接: www.cnblogs.com/lishuang224… uniapp.dcloud.io/api/ui/node…