

第一步:首頁記錄滾動到的元素距離頂部的位置
uni.createSelectorQuery().selectAll('#fix').boundingClientRect(function(res){
that.position=res[0].top
that.isGetPosition=1;
}).exec();
第二步:在小程序的滾動事件添加記錄是否到達(dá)位置
onPageScroll(e){
var that= this;
//直接寫入onload無法獲取位置信息
? if(that.isGetPosition!=1){
uni.createSelectorQuery().selectAll('#fix').boundingClientRect(function(res){
console.log(res)
that.position=res[0].top
that.isGetPosition=1;
}).exec();
}
if(that.position&&e.scrollTop>=that.position){
that.fix=1;
}else if(that.position&&e.scrollTop<that.position){
that.fix=0;
}
},
第三步:根據(jù)記錄對需要固定頭部的設(shè)置不同類名設(shè)置
:class="[fix==1 ? 'search-box-fix' : 'search-box']"
對應(yīng)css設(shè)置
.search-box{padding:20upx;display:flex;align-items:center;
&.search-box-fix{position:fixed;top:0;background:#FFFFFF;padding:20upx;width:710upx;z-index:999999;}