微信小程序?qū)Ш綑诨瑒佣ㄎ还δ苁纠?實現(xiàn)CSS3的positionsticky效果)
本文實例講述了微信小程序?qū)Ш綑诨瑒佣ㄎ还δ?。分享給大家供大家參考,具體如下:
實現(xiàn)的效果

實現(xiàn)的原理
1. 通過對scroll的監(jiān)聽獲取滾動條的scrollTop值;
2. 在導(dǎo)航的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
},
//滾動條監(jiān)聽
scroll: function (e) {
this.setData({ scrollTop: e.detail.scrollTop })
},
})
總結(jié):
1. 要獲取scrollTop,在微信小程序中我們需要:<scroll-view scroll-y="false" bindscroll="scroll" style="height:100%;"></scroll-view>;
2. 微信小程序要綁定bindscroll事件,需要綁定在scroll-view組件上,同時設(shè)置scroll-y和height。
3. 如果scroll-view的高設(shè)置100%,就需要在其外層添加一個固定高的盒子,否則監(jiān)聽不會生效。
4. 通過scroll事件獲取scrollTop:this.setData({ scrollTop: e.detail.scrollTop })
5. 導(dǎo)航欄class的切換:
scrollTop > 360 ? 'page-group-position' : ''
實質(zhì):
scrollTop > 360 ? 'fixed' : 'relative'
缺點:
1. 由于有獲取scrollTop的過程,所以會出現(xiàn)定位不及時,也就是導(dǎo)航閃動的效果;
2. 沒有原生CSS3的position:sticky流暢,體驗比較差;
3. 由于我目前還未找到直接獲取page-group的offsetTop方法,所以直接采用的是360固定值,此效果是在蘋果6進行的測試。
此效果只是提供一個思路,不建議使用在項目中,體驗太差,有待優(yōu)化。如果有更好思路的大神,敬請指教。
Demo源碼:
點擊此處本站下載。
希望本文所述對大家微信小程序開發(fā)有所幫助。
相關(guān)文章
微信小程序?qū)崿F(xiàn)天氣預(yù)報功能(附源碼)
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)天氣預(yù)報功能(附源碼),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
javascript寫的異步加載js文件函數(shù)(支持數(shù)組傳參)
這篇文章主要介紹了javascript寫的異步加載js文件函數(shù),同時支持單個文件和多個文件(數(shù)組傳參),但不兼容IE6,需要的朋友可以參考下2014-06-06
next.js?getServerSideProps源碼解析
這篇文章主要為大家介紹了next.js?getServerSideProps源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10

