微信小程序顶部swiper切换功能的实现

在微信小程序开发文档中提供了在json文件中配置tab切换的方法,那便是tabBar,其底层原理就是几个页面的来回切换,而且此tab只能放在网页底部或者头部且有个数限制,局限性非常大。那么当我们有一个需求是实现一个页面下tab切换功能而并不局限于在app.json中配置,在微信小程序中又该怎么做呢?

话不多说,上源码:

WXML:

<view class="swiper-tab">
    <block wx:for="{{navBar}}">
        <view class="swiper-tab-list {{currentTab==index ? 'on' : ''}}" data-current="{{index}}" bindtap="swichNav">
            {{item}}
        </view>
    </block>
</view>
<swiper current="{{currentTab}}" style="height:{{winHeight - 42}}px" class="swiper-box" duration="300" bindchange="bindChange">
    <block wx:for="{{navBar}}">
        <swiper-item>
            <view>{{item}}</view>
        </swiper-item>
    </block>
</swiper>

用三元表达式判断currentTab==Num是否为真,如果为真,动态添加on类名,执行标记样式,这样就实现了上面list列表的切换,至于内容重定义了data下的currentTab,让其与之对应显示,这样一个简单的tab切换功能就实现了,而且不受位置的限制,更改css样式可随意布局

=================
WXSS:

.swiper-tab {
    width: 100%;
    text-align: center;
    line-height: 40px;
}

.swiper-tab-list {  
	font-size: 30rpx;
    display: inline-block;
    width: 33.33%;
    color: #777777;
}

.on { 
	color: blue;
    border-bottom: 2px solid blue;
}

.swiper-box { 
	display: block; 
	height: 100%; 
	width: 100%; 
	overflow: hidden; 
}

.swiper-box view {
    text-align: center;
}

JS:

Page({
    data: {
        winWidth: 0,
        winHeight: 0,
        currentTab: 0,
        navBar: ['产品','金融','理财']
    },
    onLoad: function() {

        var that = this;

        /**
         * 获取当前设备的宽高
         */
        wx.getSystemInfo( {

            success: function( res ) {
                that.setData( {
                    winWidth: res.windowWidth,
                    winHeight: res.windowHeight
                });
            }

        });
    },
      
 //  tab切换逻辑
    swichNav: function( e ) {

        var that = this;

        if( this.data.currentTab === e.target.dataset.current ) {
            return false;
        } else {
            that.setData( {
                currentTab: e.target.dataset.current
            })
        }
    },

    bindChange: function( e ) {

        var that = this;
        that.setData( { currentTab: e.detail.current });

    },
})

效果图:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PinkSir

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值