Donutsapps 2019-01-28
一、前言
做复杂的小程序就与web页面的区别原来越小了,一些web页面的功能会被要求添加到微信小程序页面中。
二、功能
页面在滑动的时候顶部页面导航跟随滑动,当点击导航中的任意一项时返回页面顶部。
三、实现
wxml代码:
<view class='container'> <view class='navigation {{pageVariable.isFloat == true ? "float-navigation":""}}'> <view class='{{policyFilter.curSelectNavigationItemFormate(pageVariable.curSelectedItemId,"0")}}' data-id='0' catchtap='selectNavigationItem'>全部</view> <view class='{{policyFilter.curSelectNavigationItemFormate(pageVariable.curSelectedItemId,"1")}}' data-id='1' catchtap='selectNavigationItem'>保障中</view> <view class='{{policyFilter.curSelectNavigationItemFormate(pageVariable.curSelectedItemId,"2")}}' data-id='2' catchtap='selectNavigationItem'>已生效</view> <view class='{{policyFilter.curSelectNavigationItemFormate(pageVariable.curSelectedItemId,"3")}}' data-id='3' catchtap='selectNavigationItem'>未生效</view> </view> </view>
wxss代码:
.navigation { /*导航样式*/ width: 100%; display: flex; justify-content: space-around; align-items: center; height: 80rpx; background-color: #fff; font-size: 28rpx; color: #333; font-weight: 500; box-shadow: inset 0 0 0 0 rgba(0, 0, 0, 0.30); } .float-navigation { /*导航浮动起来的css*/ position: fixed; top: 0; z-index: 1000; } .navigation-item-selected { /*导航项选中的样式*/ color: #40a0ee; height: 80rpx; line-height: 80rpx; border-bottom: 3rpx solid #40a0ee; }
js代码:
Page({ data:function () { var model = {}; model.pageVariable = { curSelectedItemId:'0', //顶部导航栏,当前选中的项 isFloat:false, //控制导航栏浮动 } return model; }(), /** * 选择导航 */ selectNavigationItem:function(e){ this.setData({ 'pageVariable.curSelectedItemId': e.currentTarget.dataset.id, 'pageVariable.isFloat':false }); wx.pageScrollTo({ scrollTop: 0, }); this.initData(e.currentTarget.dataset.id); //加载数据 }, onPageScroll:function(res){ if (res.scrollTop >= 1){ //开始滚动 if (!this.data.pageVariable.isFloat){ this.setData({ 'pageVariable.isFloat':true }); } }else{ this.setData({ 'pageVariable.isFloat': false }); } } })
总结:
这个功能的实现主要是通过onPageScroll页面注册函数来实现页面滚动,通过pageScrollTo api实现导航选项在被选中时返回到页面顶部。