完整教程:小程序点击菜单栏实现样式动态切换

小程序点击菜单栏背景样式动态切换

前言:今天做一个小程序项目,要做一个菜单栏动态切换的功能,因为这种需求很常见,这次干脆记录一下,帮助别人的同时,自己下次也可以直接照搬使用。

效果截图如下:

在这里插入图片描述

就是点击图片上的 商品类型的子菜单 和 排序方式的子菜单的时候 能够实现切换。

wxml代码:
<view class="tabs">
  <view class="tab_title">商品类型:</view>
    <view class="tab">
      <view class="tab_item {{currentIndex === index ? 'active' : ''}}"
      wx:for="{{leixing}}"
      wx:key="*this"
      bind:tap="changeLeixing" data-index="{{index}}">
      {
      {item
      }
      }</view>
        </view>
          </view>
            <view class="tabs">
              <view class="tab_title">排序方式:</view>
                <view class="tab">
                  <view class="tab_item {{currentIndex2 === index ? 'active' : ''}}"
                  wx:for="{{paixu}}"
                  wx:key="*this"
                  bind:tap="changePaixu" data-index="{{index}}">
                  {
                  {item
                  }
                  }</view>
                    </view>
                      </view>
wxss代码:
.tabs {
width: 690rpx;
margin-top: 20rpx;
}
.tabs .tab_title {
margin-left: 20rpx;
}
.tabs .tab {
display: flex;
align-items: center;
width: 100%;
margin-left: 10rpx;
margin-top: 15rpx;
}
.tabs .tab .tab_item {
display: flex;
justify-content: center;
align-items: center;
padding: 10rpx 20rpx;
border-radius: 20rpx;
margin: 0rpx 10rpx;
}
.tabs .tab .active {
background-color: #EBB8B6;
color: #ffffff;
}
*如果你使用的是less 就复制下面这段
.tabs{
width: 690rpx;
margin-top: 20rpx;
.tab_title{
margin-left: 20rpx;
}
.tab{
display: flex;
align-items: center;
width: 100%;
margin-left: 10rpx;
margin-top: 15rpx;
.tab_item{
display: flex;
justify-content: center;
align-items: center;
padding: 10rpx 20rpx;
border-radius: 20rpx;
margin: 0rpx 10rpx;
}
.active{
background-color: #EBB8B6;
color: #ffffff;
}
}
}
js对应的代码
**首先是小程序js中data里面的变量:**
data: {
currentIndex:0, // 类型的索引
currentIndex2:0, // 排序的索引
leixing:["全部","热销","新品"],
paixu:["默认","价格↑","价格↓","销量"],
},
**两个菜单切换的点击函数**(函数名可以自己随便取,但是wxml里面的点击的绑定事件的函数名也要跟着换)
// 切换类型
changeLeixing(e){
console.log(e.currentTarget.dataset.index);
this.setData({
currentIndex:e.currentTarget.dataset.index
});
},
// 切换排序方式
changePaixu(e){
console.log(e.currentTarget.dataset.index);
this.setData({
currentIndex2:e.currentTarget.dataset.index
});
},

结束语:只要每天有收获,不论多少,那就是进步,加油!!!

posted @ 2025-08-07 13:19  yjbjingcha  阅读(62)  评论(0)    收藏  举报