小程序tab切换效果

效果一

wxml;

<view class="page_list flex">
    <block wx:for="{{30}}">
       <view class="page_li sub {{index == Area ? 'active':''}}" bindtap="chooseArea" id="{{index}}">河南省</view>
    </block>
</view>

wxss:

.page_list{background: #fff;display: flex;}
.page_list .page_li{height: 100rpx;line-height: 100rpx;flex: 1;text-align: center;}
.page_list .page_li.active{color: red;}

wxjs:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    Area: false,

  },
 
  chooseArea: function (e) {
    let dataId = e.currentTarget.id;
    this.setData({
      Area: dataId
    })
  },
  
})

效果二

wxml:

<scroll-view scroll-x="true" class="tab_h sub" scroll-with-animation="true" current='{{selectedTitle}}' scroll-left="{{scrollLeft}}">
    <block wx:for="{{categoryallList}}">
      <view id="{{index}}" bindtap="bindtap" class="tab_item tab_item-{{index}} {{index==selectedTitle ? 'active' : ''}}">
      {{item.name}}
      </view>
    </block>
</scroll-view>

wxss:

.tab_h{height: 80rpx; 100%; box-sizing: border-box;overflow: hidden;line-height: 80rpx;font-size: 14px; white-space: nowrap;background: #fff;}
.tab_h .tab_item{margin:0 36rpx;display: inline-block;position: relative;}
.tab_h .tab_item.active{color: #f6414a;font-weight: bold;}
.tab_h .tab_item:after{ content: "";display: block;height: 8rpx; 0;background: #f6414a;position: absolute; bottom: 0;left: 50%;border-radius: 100rpx;-webkit-transition: all 0.2s ease-in;transition: all 0.2s ease-in;-webkit-transform:translateX(-50%);transform:translateX(-50%);}
.tab_h .tab_item.active:after{right: 0; 100%;}

wxjs:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollLeft: 0,
    selectedTitle: "0",
    categoryallList:[{
      name:'切换一'
    },{
      name:'切换二'
    },{
      name:'切换三'
    },{
      name:'切换四'
    },{
      name:'切换五'
    },{
      name:'切换六'
    },{
      name:'切换七'
    },{
      name:'切换八'
    }]

  },
  //判断当前滚动超过一屏时,设置tab标题滚动条。
bindtap: function (e) {
    var obj = this;
    obj.setData({
      selectedTitle: e.currentTarget.id
      
    });
    console.log(e)
    wx.createSelectorQuery().select('.tab_item-' + e.currentTarget.id).boundingClientRect(
      function (rect) {
        
        wx.getSystemInfo({
          success: function (res) {
            wx.createSelectorQuery().select('.tab_h').scrollOffset(function (scroll) {
              obj.setData({
                scrollLeft: scroll.scrollLeft + rect.width / 2 + rect.left - res.windowWidth / 2,
                selectedTitle: e.detail.current
              });
            }).exec()
          }
        })
      }
    ).exec()
  },
})
  

原文地址:https://www.cnblogs.com/liweitao/p/12794392.html