本文實例講述了微信小程序自定義可滑動頂部TabBar選項卡實現頁面切換功能。分享給大家供大家參考,具體如下:
頂部滾動選項卡
話不多說,直接上代碼
pages/home/home.wxml
<scroll-view scroll-x="true" style='width: 100%; white-space:nowrap; '><!-- tab --><view class="tab"><view class="tab-nav" style='font-size:12px'><view wx:for="{{tabnav.tabitem}}" bindtap="setTab" data-tabindex="{{index}}" style="min-width:20%;max-width:20%;text-align:center;height: 80rpx;background: #fff;border-bottom:{{index>4?'1rpx solid #ddd;':''}}">{{item.text}}</view><view><view class="tab-line" style="width:{{100/tabnav.tabnum}}%;transform:translateX({{100*showtab}}%);"></view></view></view></view></scroll-view><swiper current="{{currentTab}}" class="swiper-box" duration="300" style="height:150rpx" bindchange="bindChange"><swiper-item><view>分類1</view></swiper-item><swiper-item><view>分類2</view></swiper-item><swiper-item><view>分類3</view></swiper-item><swiper-item><view>分類4</view></swiper-item><swiper-item><view>分類5</view></swiper-item><swiper-item><view>分類6</view></swiper-item></swiper>
pages/home/home.wxss
.tab {display: flex;flex-direction: column;}.tab-nav {border-bottom: 1rpx solid #ddd;width: 100%;height: 80rpx;display: flex;line-height: 79rpx;position: relative;}.tab-line {position: absolute;left: 0;bottom: -1rpx;height: 4rpx;background: #f7982a;transition: all 0.3s;}.tab-content {flex: 1;overflow-y: auto;overflow-x: hidden;}/*選項卡頁面聯動切換*/.swiper-tab {width: 100%;border-bottom: 2rpx solid #777;text-align: center;line-height: 80rpx;}.swiper-tab-list {font-size: 30rpx;display: inline-block;width: 33.33%;color: #777;}.on {color: #da7c0c;border-bottom: 1rpx solid #da7c0c;}.swiper-box {display: block;height: 100%;width: 100%;overflow: hidden;}.swiper-box view {text-align: center;}
pages/home/home.js
Page({data: {showtab: 0, //頂部選項卡索引tabnav: {tabnum: 5,tabitem: [{"id": 0,"text": "分類1"},{"id": 1,"text": "分類2"},{"id": 2,"text": "分類3"},{"id": 3,"text": "分類4"},{"id": 4,"text": "分類5"},{"id": 5,"text": "分類6"}]},productList: [],// tab切換currentTab: 0,},onLoad: function () {},setTab: function (e) {var that = thisthat.setData({showtab: e.currentTarget.dataset.tabindex})if (this.data.currentTab === e.currentTarget.dataset.tabindex) {return false;} else {that.setData({currentTab: e.currentTarget.dataset.tabindex})}},/*** 滑動切換tab*/bindChange: function (e) {var that = this;that.setData({ currentTab: e.detail.current,showtab: e.detail.current});}})
該代碼實現基于兩個大神的代碼,,在兩位大神的基礎上衍生出的可滾動的頂部選項卡,在此致謝。代碼缺陷:當向右滑動到第6個頁面的時候選項卡沒有自動滑動。
希望本文所述對大家微信小程序開發有所幫助。
新聞熱點
疑難解答