微信小程序切换选中状态

 实现的主要思路是根据每一项的index值,动态改变idx值,当index==idx值的时候,添加点击选中样式的类名。

wxml:

<scroll-view scroll-x="true">
  <view class="scroll-x">
    <view wx:for-items="{{scrolls}}" wx:key="name">
      <view class="view {{index==idx?'_left':'left'}}" data-index="{{index}}" bindtap="goIndex">{{item}}</view>
    </view>
  </view>
</scroll-view>

接下来是css:

.scroll-x {
  display: flex;
  flex-direction: row;
}
.view {
  width: 200px;
  text-align: center;
}
.active,._left{
  color: #fff;
  background-color: #000;
  border-bottom:1px solid red;
}

最后是js

  data: {
    scrolls: ['待审批订单','已审批订单'],
    idx: 0
  },

  goIndex (e) {
     this.setData({
       idx:e.currentTarget.dataset.index,
     })
  },
原文地址:https://www.cnblogs.com/tomingto/p/13984454.html