uniapp项目的吸顶效果的实现

uni.createSelectorQuery()可以创建一个选择器,类似于css选择器一样,可以选中一个元素,通过boundingClientRect可以获得元素的几何位置信息,通过top可以判断元素距离视口顶部的距离。

js文件

data(){
 return{
  isFixedTop:false,
 }
},
onLoad(){
 uni.pageScrollTo({
  scrollTop:0,
  duration:0
 })
 setTimeout(()=>{
  this.GetTop()
  // this.aaa()
 },1000)
},
//监测页面滑动
onPageScroll(e) {
 if(e.scrollTop > this.Topdistance){
  this.isFixedTop = true
 }else{
  this.isFixedTop = false
 }
},
methods:{
 GetTop(){
  // 获取元素距离顶部的距离
  var _this=this
  uni.getSystemInfo({
   success:(resu)=>{
    const query = uni.createSelectorQuery()
    query.select('#box').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
     _this.Topdistance=res[0].top
     
    })
   },
   fail:(res)=>{}
  })
 },
}

页面

<view :class="[(isFixedTop) ? 'fixedTop' : '']" id="box" class="box bgwhite">
 <view class="m-lr-30 row just-btw p-tb-30">
  <view class="row alignitems">
   <image src="../../static/quanbu_icon.png" mode="aspectFit" style="width:40rpx;height:40rpx;"></image>
   <view class="f30 weight500 m-l-20">全部品牌</view>
  </view>
  <!-- <image src="../../static/search_icon.png" mode="aspectFit" style="width:38rpx;height:35rpx;"></image> -->
 </view>
</view>

css

.fixedTop{
 position: fixed;
 width:100%;
 top:0;
 left: 0;
 z-index: 999;
}

猜你喜欢

转载自blog.csdn.net/weixin_61728046/article/details/127355043