本文实例为大家分享了微信小程序实现点击导航条切换页面的具体代码,供大家参考,具体内容如下
我录制了个gif如下,黄色部分是不可以滑动的,蓝色部分可以滑动。
代码解说:
首先我在js自定义了navState参数用于判断导航的当前状态,定义了data-index用于js中动态修改导航的当前状态,nav-switch-style为选择导航条时的样式,不可滑动视图切换很简单,用wx:if判断状态显示相应页就好了,滑动页视图切换要用到swiper和 swiper-item,用bindchang方法监听滑块,current 改变时会触发 change 事件(还有个bindanimationfinish方法监听也是可以用的,详细请看官方文档)动态的绑定了current滑块的index,这样就可以实现点击导航条滑块跟着滚动,相反的,当滑动滑块时,就可以根据current的值来动态修改导航的状态了。
wxml代码:
<!-- 导航条 --><view class="nav"><view bindtap="navSwitch" data-index="0" class="{{navState==0 ? 'nav-switch-style':''}}">页面一</view><view bindtap="navSwitch" data-index="1" class="{{navState==1 ? 'nav-switch-style':''}}">页面二</view><view bindtap="navSwitch" data-index="2" class="{{navState==2 ? 'nav-switch-style':''}}">页面三</view></view><!-- 不可滑动页 --><view><view wx:if="{{navState==0}}" class="style-default">1</view><view wx:elif="{{navState==1}}" class="style-default">2</view><view wx:else="{{navState==2}}" class="style-default">3</view></view><!-- 滑动页 --><swiper bindchange="bindchange" current="{{navState}}"><block><swiper-item><view class="style-roll"><text>左右可滑动1</text></view></swiper-item><swiper-item><view class="style-roll"><text>左右可滑动2</text></view></swiper-item><swiper-item><view class="style-roll"><text>左右可滑动3</text></view></swiper-item></block></swiper>
js代码:
Page({data: {navState: 0,//导航状态},//监听滑块bindchange(e) {// console.log(e.detail.current)let index = e.detail.current;this.setData({navState:index})},//点击导航navSwitch: function(e) {// console.log(e.currentTarget.dataset.index)let index = e.currentTarget.dataset.index;this.setData({navState:index})},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {},})
wxss代码:
.nav{display: flex;justify-content: space-around;padding: 20rpx;background-color: rgb(129, 241, 55);font-size: 30rpx;}.nav-switch-style{color: snow;}.style-default{background-color: rgb(247, 229, 130);padding: 100rpx 0;text-align: center;}.style-roll{background-color: rgb(130, 177, 247);padding: 100rpx 0;text-align: center;}