小程序如何实现tab切换,一部到位

笔者之前尝试着其他教程:使用swiper来做切换。但是小程序中swiper存在很多限制,比如高度的限制,所以放弃了这种方案,本文将提供另一个方案。

小程序实现tab切换很简单,只需要完成两部分。
1.编写页面
2.编写js触发事件

先上效果图

小程序如何实现tab切换,一部到位_第1张图片

接下来介绍页面代码:

控制切换的Tab

<view class="swiper-tab">
    <view class="swiper-tab-item {{currentTab==0?'active':''}}" data-current="0" bindtap="clickTab">做什么view>
    <view class="swiper-tab-item {{currentTab==1?'active':''}}" data-current="1" bindtap="clickTab">推荐站点view>
    <view class="swiper-tab-item {{currentTab==2?'active':''}}" data-current="2" bindtap="clickTab">作者view>
  view>

要切换的内容


    <scroll-view>
      <text>暂无内容1text>
    scroll-view>
  view>
  
    <scroll-view>
      <text>暂无内容2text>
    scroll-view>
  view>
  
    <scroll-view>
      <text>暂无内容3text>
    scroll-view>
  view>

js触发事件 在对应页面的js文件中加入如下方法。

//点击切换
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
    }

页面样式 这个不重要,可以按照个人效果随便修改。

/* pages/about/about.wxss */
.about_page{
  margin: 0 10px;
}
.swiper-tab{
    width: 100%;
    /* border-bottom: 2rpx solid #ccc; */
    text-align: center;
    height: 88rpx;
    line-height: 88rpx;
    display: flex;
    flex-flow: row;
    justify-content: space-between;
    color: #ccc;
    font-size: 16px;
}
.swiper-tab-item{
    width: 30%; 
    color:#434343;
}
.active{
    color:#F65959;
    /* border-bottom: 4rpx solid #F65959; */
    font-size: 16px;
    font-weight: bold;
}
.juzhong{
  margin: 0 auto;
}
.domain{
  background-color: #fff;
  height: 100%;
  margin:0 10px;
}
.show{
  display: block;
}
.hidden{
  display: none;
}

你可能感兴趣的:(小程序)