實現的效果
實現的原理
- 通過對scroll的監聽獲取滾動條的scrollTop值;
- 在導航的class判斷scrollTop;
- 切換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 })
},
})
總結:
- 要獲取scrollTop,在微信小程序中我們需要:
<scroll-view scroll-y="false" bindscroll="scroll" style="height:100%;"></scroll-view>
; - 微信小程序要綁定bindscroll事件,需要綁定在scroll-view組件上,同時設置scroll-y和height。
- 如果scroll-view的高設置100%,就需要在其外層添加一個固定高的盒子,否則監聽不會生效。
- 通過scroll事件獲取scrollTop:
this.setData({ scrollTop: e.detail.scrollTop })
- 導航欄class的切換:
scrollTop > 360 ? 'page-group-position' : ''
實質:
scrollTop > 360 ? 'fixed' : 'relative'
缺點:
1. 由於有獲取scrollTop的過程,所以會出現定位不及時,也就是導航閃動的效果;
2. 沒有原生CSS3的position:sticky流暢,體驗比較差;
3. 由於我目前還未找到直接獲取page-group的offsetTop方法,所以直接采用的是360固定值,此效果是在蘋果6進行的測試。
此效果只是提供一個思路,不建議使用在項目中,體驗太差,有待優化。如果有更好思路的大神,敬請指教。