微信小程序tab切换(点击标题切换,滑动屏幕切换)

效果图:
在这里插入图片描述

WXML文件

<view class="tab">
  <scroll-view class="nav" scroll-x="true" scroll-left="{{scrollLeft}}">
      <block wx:for="{{allTitle}}" wx:for-index="idx" wx:key="idex">
        <view class="nav-item {{currentIndex==idx ? 'active' : ''}}" data-current="{{idx}}" bindtap="changeTitle">{{item.title}}</view>
      </block>
  </scroll-view>
  <swiper class="content-container" current="{{currentIndex}}" circular="{{false}}" bindchange="changeContent">
    <swiper-item class="content">客厅</swiper-item>
    <swiper-item class="content">厨房</swiper-item>
    <swiper-item class="content">卧室</swiper-item>
    <swiper-item class="content">KTV</swiper-item>
    <swiper-item class="content">浴室</swiper-item>
    <swiper-item class="content">广场</swiper-item>
    <swiper-item class="content">公园</swiper-item>
    <swiper-item class="content">博物馆</swiper-item>
  </swiper>
</view>

JS文件

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    allTitle:[
      { id: 0, title: '客厅'},
      { id: 1, title: '厨房'},
      { id: 2, title: '卧室'},
      { id: 3, title: 'KTV'},
      { id: 4, title: '浴室'},
      { id: 5, title: '广场'},
      { id: 6, title: '公园'},
      { id: 7, title: '博物馆'}
    ],
    currentIndex: 0, //当前选中标题的下标
    scrollLeft: 0, //tab滚动条的位置
  },

  onLoad: function () {

  },

  //点击切换标题
  changeTitle(event){
    let index = event.target.dataset.current;//当前点击标题的index
    this.setData({
      currentIndex:index
    })
  },

  //滑动切换内容
  changeContent(event){
    let current = event.detail.current;
    let singleNavWidth = wx.getSystemInfoSync().windowWidth / 5;
    this.setData({
      currentIndex: current,
      scrollLeft: (current - 2) * singleNavWidth
    });
  }
})

WXSS文件

page{
  width: 100%;
  height: 100%;
}
.tab {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.nav {
  height: 80rpx;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  line-height: 80rpx;
  font-size: 16px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
}


.nav-item {
  width: 20%;
  display: inline-block;
  text-align: center;
}

.active {
  color: #FF6471;
  position: relative;
}

.active:after{
  content: "";
  display: block;
  width:100%;
  height: 5rpx;
  border-radius: 8rpx;
  background: #FF6471;
  position: absolute;
  bottom: 0;
}

.content-container {
  padding-top: 180rpx;
  height: 100%;
  width: 100%;
  text-align: center;
}

.content{
  margin-top:180rpx;
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值