微信小程序切换选中状态

项目场景:类似于平时我们在传统web端开发tab栏的选中状态效果,我们通常在web端通过获取元素。添加样式样式类名,兄弟元素移除类名。

那么我们如何在小程序中实现一个,区域可以左右滑动的tab栏选中效果:

首先我们要使用微信小程序提供的scroll-view视图标签;

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

<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}}" @tap='goIndex'>{{item}}</view>
    </view>
  </view>
</scroll-view>

 接下来是css:

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

js:

goIndex (e) {
    this.idx = e.currentTarget.dataset.index; 
    // console.log('每个index',index)
  };
 data = {
    userInfo: '',
    scrolls: ['tab1','tab2', 'tab3', 'tab4', 'tab5', 'tab6'],
    idx: 0
  };

 以上代码:基于wepy开发的小程序。和原生小程序js有出入。可以看下wepy开发框架。wepy框架

猜你喜欢

转载自blog.csdn.net/qq_29557739/article/details/89006716