微信小程序----导航栏滑动定位(实现CSS3的position:sticky效果)


DEMO下载

实现的效果

微信小程序实现position:sticky

实现的原理

  1. 通过对scroll的监听获取滚动条的scrollTop值;
  2. 在导航的class判断scrollTop;
  3. 切换position:fixed与position:relative。

WXML

<view style="height:100%;position:fixed;width:100%;"> <scroll-view scroll-y="false" bindscroll="scroll" style="height:100%;"> <view class="page-bottom-content"> <text>{{text}}</text> </view> <view class="page-banner"> banner </view> <view class="page-group {{scrollTop > 360 ? 'page-group-position' : ''}}"> <view class="page-nav-list"><text>首页</text></view> <view class="page-nav-list"><text>活动</text></view> <view class="page-nav-list"><text>菜单</text></view> <view class="page-nav-list"><text>我的</text></view> </view> <view class="goods-list"> goods-list </view> </scroll-view> </view>

WXCSS

.page-banner{height: 500rpx;background-color: greenyellow;padding: 20rpx;color:#fff;}
.page-group{ display: table; background-color: blueviolet; width: 100%; table-layout: fixed; position: relative; top: 0; left: 0; }
.page-group-position{ position: fixed; }
.page-nav-list{ padding:30rpx 0 ; display: table-cell; text-align: center; color: #fff; }
.goods-list{ height: 2000rpx; background-color: green; padding: 20rpx; color:#fff; }

JS

Page({
  data: {
    scrollTop: null
  },
  //滚动条监听
  scroll: function (e) {
    this.setData({ scrollTop: e.detail.scrollTop })
  },
})

总结:

  1. 要获取scrollTop,在微信小程序中我们需要:<scroll-view scroll-y="false" bindscroll="scroll" style="height:100%;"></scroll-view>
  2. 微信小程序要绑定bindscroll事件,需要绑定在scroll-view组件上,同时设置scroll-y和height。
  3. 如果scroll-view的高设置100%,就需要在其外层添加一个固定高的盒子,否则监听不会生效。
  4. 通过scroll事件获取scrollTop:this.setData({ scrollTop: e.detail.scrollTop })
  5. 导航栏class的切换:

    scrollTop > 360 ? 'page-group-position' : ''
    实质:
    scrollTop > 360 ? 'fixed' : 'relative'

缺点:
1. 由于有获取scrollTop的过程,所以会出现定位不及时,也就是导航闪动的效果;
2. 没有原生CSS3的position:sticky流畅,体验比较差;
3. 由于我目前还未找到直接获取page-group的offsetTop方法,所以直接采用的是360固定值,此效果是在苹果6进行的测试。

此效果只是提供一个思路,不建议使用在项目中,体验太差,有待优化。如果有更好思路的大神,敬请指教。

其他

我的博客,欢迎交流!

我的CSDN博客,欢迎交流!

微信小程序专栏

前端笔记专栏

微信小程序实现部分高德地图功能的DEMO下载

微信小程序实现MUI的部分效果的DEMO下载

微信小程序实现MUI的GIT项目地址

微信小程序实例列表

前端笔记列表

游戏列表


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM