微信小程序实现顶部tab切换

2025-10-31 03:42:51

1、打开开发者工具,新建项目在项目的pages文件夹下创建一个mypage文件夹,并在文件夹内新建mypage,在app.json中将mypage设为第一页面

微信小程序实现顶部tab切换

2、在mypage.wxml中添加代码如下:

<view class="outter">

 <view data-tapid="0" class="slid-item {{currentid==0?'on':''}}" bindtap="tap">读书</view>

 <view data-tapid="1" class="slid-item {{currentid==1?'on':''}}" bindtap="tap">出游</view>

 <view data-tapid="2" class="slid-item {{currentid==2?'on':''}}" bindtap="tap">观影</view>

</view>

data-tapid是事件触发时的会存在事件对象的 target.dataset.tapid中

currentid是js文件中变量,通过这个变量值,控制样式

微信小程序实现顶部tab切换

3、在mypage.wxss中添加代码如下:

.outter{

 display: flex;

 width: 100%;

 justify-content: center;

 border-bottom: 2rpx solid black

}

.slid-item{

 margin-left: 20rpx;

 margin-right: 20rpx;

}

.on{

 border-bottom: 3rpx solid red;

}

微信小程序实现顶部tab切换

4、在mypage.js文件中,添加currentid变量,代码如下:

微信小程序实现顶部tab切换

5、编译代码,在左侧模拟器查看效果,基本实现了要求,下一步动态更改选中的

currentid

微信小程序实现顶部tab切换

6、在mypage.js文件添加一个事件函数,代码如下:

tap:function(e){

   console.log(e)

   console.log(e.target.dataset.tapid)

   var that = this

   that.setData({currentid:e.target.dataset.tapid})

 }

console.log(e)是测试观察输入用的

微信小程序实现顶部tab切换

7、编译运行,在左侧模拟器切换tab会发现标签下的红色底边框跟随切换

微信小程序实现顶部tab切换

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢