小程序頂部導航欄,可滑動,可動態選中放大

最近在研究小程序頂部導航欄時,學到了一個不錯的導航欄,今天就來分享給大家。

老規矩,先看效果圖


可以看到我們實現瞭如下功能

  • 1,頂部導航欄
  • 2,可以左右滑動的導航欄
  • 3,選中條目放大

原理其實很簡單,我這裏把我研究後的源碼發給大家吧。

wxml文件如下

<!-- 導航欄 -->
<scroll-view scroll-x class="navbar" scroll-with-animation scroll-left="{{scrollLeft}}rpx">
  <view class="nav-item" wx:for="{{tabs}}" wx:key="id" bindtap="tabSelect" data-id="{{index}}">
    <view class="nav-text {{index==tabCur?'tab-on':''}}">{{item.name}}</view>
  </view>
</scroll-view>

wxss文件如下

/* 導航欄佈局相關 */
.navbar {
  width: 100%;
   height: 90rpx;
  /* 文本不換行 */
  white-space: nowrap;
  display: flex;
  box-sizing: border-box;
  border-bottom: 1rpx solid #eee;
  background: #fff;
  align-items: center;
  /* 固定在頂部 */
  position: fixed;
  left: 0rpx;
  top: 0rpx;
}

.nav-item {
  padding-left: 25rpx;
  padding-right: 25rpx;
  height: 100%;
  display: inline-block;
  /* 普通文字大小 */
  font-size: 28rpx;
}

.nav-text {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 4rpx;
  box-sizing: border-box;
}

.tab-on {
  color: #fbbd08;
  /* 選中放大 */
  font-size: 38rpx !important;
  font-weight: 600;
  border-bottom: 4rpx solid #fbbd08 !important;
}

js文件如下

// pages/test2/test2.js
Page({
  data: {
    tabCur: 0, //默認選中
    tabs: [{
        name: '等待支付',
        id: 0
      },
      {
        name: '待發貨',
        id: 1
      },
      {
        name: '待收貨',
        id: 2
      },
      {
        name: '待簽字',
        id: 3
      },
      {
        name: '待評價',
        id: 4
      },
      {
        name: '五星好評',
        id: 5
      },
      {
        name: '差評訂單',
        id: 6
      },
      {
        name: '編程小石頭',
        id: 8
      },
      {
        name: '小石頭',
        id: 9
      }
    ]

  },

  //選擇條目
  tabSelect(e) {
    this.setData({
      tabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 2) * 200
    })
  }
})

代碼裏註釋很明白了,大家自己跟着多敲幾遍就可以了。後面會更新更多小程序相關的知識,請持續關注。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章