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

 时间:2026-02-15 08:28:19

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切换

  • Axure怎么制作进度条的效果?
  • 如何利用Axure RP 8设计工具控制密码显示和隐藏
  • 猫盘删文件如何删的干净如何能恢复
  • navicate如何导出数据库
  • spring整合mybatis需要的依赖
  • 热门搜索
    岳阳旅游公司 广州从化旅游 上饶旅游网 旅游者腹泻 邮船旅游 黄花城水长城旅游区 拉斯维加斯旅游费用 旅游胜地风景图片 2人被列入全国旅游市场黑名单 旅游路线设计方案