uniapp-页面滚动-元素固定置顶
//使用css变量
<view :class="{'isPosition':isFixed}" :style="styleVar">
.head_height{
height: var(--head-height);
}
.isPosition{
position: fixed;
top: var(--head-height);
left: 0;
right: 0;
z-index: 9;
}
data:{
isFixed: false,
top: '',
bottom:108,
height:44,
},
computed:{ //巧妙运用style var变量
styleVar() {
//#ifdef H5
return `--head-height:${this.height} px`
//#endif
//#ifdef MP-WEIXIN
return `--head-height:0`
//#endif
},
heightVar() {
//#ifdef H5
return `--head-height:${this.height+48} px`
//#endif
//#ifdef MP-WEIXIN
return `--head-height:0`
//#endif
}
},
methods: {
getScroll(){ //滚动悬浮
let that =this;
//获取设备参数
uni.getSystemInfo({
success: function (res) {
//#ifdef H5
that.height=res.windowTop;
that.bottom=res.windowBottom;
//#endif
//#ifdef MP-WEIXIN || APP-PLUS
that.height=res.safeAreaInsets.top;
// that.bottom=Math.abs(res.safeAreaInsets.bottom);
that.bottom=0
//#endif
}
});
// 获取元素参数
const query = uni.createSelectorQuery().in(this);
query.select('#header_h').boundingClientRect(data => {
this.top =data.height
}).exec();
},
},
mounted() {
//createSelectorQuery 要在这个生命周期函数执行否着报错
this.getScroll()
},
onPageScroll(e) { //页面滚动判断元素与距离顶部的距离
if(this.top < e.scrollTop){
this.isFixed=true;
}else{
this.isFixed=false;
}
}