需要固定的元素加上動態樣式綁定
:style="isTop == 1 ? 'position:fixed;background:#FFFFFF;z-index:9;top:0' :''"
變量istop要定義在data中,默認0
頁面生命周期mouted,和onLoad同一層級,
mounted() {
console.log('mounted 組件掛載完畢狀態===============》');
const query = uni.createSelectorQuery().in(this);
query.select('#scrollView').boundingClientRect(data => {
console.log("得到布局位置信息" + JSON.stringify(data));
console.log("節點離頁面頂部的距離為" + data.top);
this.myScroll = data.top
}).exec();
},
這個#scrollView,此id是你需要固定的元素最外層id,這個方法的意義是針對於不同尺寸屏幕的手機的元素距離不同
onPageScroll:function(e){
if(e.scrollTop > this.myScroll){
this.isTop = 1
}else{
this.isTop = 0
}
},
這個j監聽頁面滾動距離,和onload同級,
當滾動距離超過元素距離頁面頂部的距離時,就將是否定位改為true,否則就為false
完成