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

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

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

效果截图如下:

在这里插入图片描述

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

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
    });
  },

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值