微信小程式——漂亮的頂部導航欄(捲動)swiper,左右滑動切換頂部選項,向上滑動隱藏輪播圖

2020-10-10 00:00:16

1、頂部導航欄(捲動)

使用的是swiper和swiper-item來實現,左右滑動切換頂部選項,效果圖如下:
在這裡插入圖片描述

程式碼:

js

//index.js
//獲取應用範例
const app = getApp()

Page({
  data: {
    tabbar: ["熱門", "娛樂", "體育", "國內", "財經", "科技", "教育", "汽車"],
    winHeight: "", //視窗高度
    currentTab: 0, //預設當前項的值
    scrollLeft: 0 //tab標題的卷軸位置
  },

  onLoad: function () {
    let that = this;
    //  高度自適應
    wx.getSystemInfo({
      success: function (res) {
        let calc = res.windowHeight; //頂部脫離檔案流了(- res.windowWidth / 750 * 100);
        // console.log('==頂部高度==',calc)
        that.setData({
          winHeight: calc
        });
      }
    });
  },
  // 捲動切換標籤樣式
  switchTab: function (e) {
    let that = this;
    // console.log("捲動切換標籤",e)
    that.setData({
      currentTab: e.detail.current
    });
    that.checkCor();
  },
  // 點選標題切換當前頁時改變樣式
  swichNav: function (e) {
    let cur = e.currentTarget.dataset.current;
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  },
  //判斷當前捲動超過一屏時,設定tab標題卷軸。
  checkCor: function () {
    let that = this;
    if (that.data.currentTab > 3) {
      that.setData({
        scrollLeft: 300
      })
    } else {
      that.setData({
        scrollLeft: 0
      })
    }
  },
})

.wxml

<!--index.wxml-->
<view class="container">
  <!-- 頂部導航欄 -->
  <scroll-view scroll-x scroll-with-animation class="tab-view" scroll-left="{{scrollLeft}}">
    <view wx:for="{{tabbar}}" wx:key="{{index}}" class="tab-bar-item {{currentTab==index ? 'active' : ''}}"
      data-current="{{index}}" catchtap="swichNav">
      <text class="tab-bar-title">{{item}}</text>
    </view>
  </scroll-view>

  <!-- 內容 -->
  <swiper class="tab-content" current="{{currentTab}}" duration="300" bindchange="switchTab"
    style="height:{{winHeight}}px">
    <swiper-item wx:for="{{tabbar}}" wx:key="{{index}}">
      <scroll-view scroll-y class="scoll-y">
        <!--start 內容部分,可直接刪除-->
        <block wx:if="{{index ==0}}">
          <include src="../remen/remen.wxml" />
        </block>

        <block wx:if="{{index ==1}}">
          <include src="../yule/yule.wxml" />
        </block>
        <!--end 內容部分,可直接刪除-->
      </scroll-view>
    </swiper-item>
  </swiper>
</view>

.wxss

/**index.wxss**/
.container {
  /* height: 100%;
  width: 100%; */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* *******topbar******* begin*/
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}

.tab-view::before {
  content: '';
  position: absolute;
  border-bottom: 1rpx solid #eaeef1;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  bottom: 0;
  right: 0;
  left: 0;
}

.tab-view {
  width: 100%;
  height: 100rpx;
  overflow: hidden;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  background: #fff;
  white-space: nowrap;
}

.tab-bar-item {
  padding: 0;
  height: 100rpx;
  min-width: 80rpx;
  line-height: 100rpx;
  margin: 0 28rpx;
  display: inline-block;
  text-align: center;
  box-sizing: border-box;
}

.tab-bar-title {
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
  color: #999;
  font-weight: 400;
}

.active {
  border-bottom: 6rpx solid #5677fc;
}

.active .tab-bar-title {
  color: #5677fc !important;
  font-size: 36rpx;
  font-weight: bold;
}

/* *******topbar******* end*/

.scoll-y {
  height: 100%;
}

.tab-content {
  height: 100%;
  width: 100%;
}

需要完整程式碼可到這裡下載:https://download.csdn.net/download/wy313622821/12914516

2、頂部導航欄(不帶捲動)

效果圖:
在這裡插入圖片描述

.js

// pages/button/button.js
Page({
    data: {
        barList: ['熱點','新聞','趣事'],
        barIndex:0
    },
    clickBar:function(e){
        this.setData({
            barIndex:e.currentTarget.dataset.index
        })
    },
    onLoad: function (options) { 
        
    },
})

.wxml

<view class='ui_tab'>
    <view class='ui_navbar'>
        <view class='ui_navbar_item {{barIndex==index?"ui_navbar_item_on":""}}' wx:for="{{barList}}" wx:key="{{index}}" data-index="{{index}}" bindtap='clickBar'>{{item}}</view>
    </view>
    <view wx:if="{{barIndex==0}}">頁面一</view>
    <view wx:if="{{barIndex==1}}">頁面二</view>
    <view wx:if="{{barIndex==2}}">頁面三</view>
</view>

.wxss

.ui_tab {
  position: relative;
  /* border-top:2rpx solid #ccc;  橫線*/
}

.ui_navbar {
  display: flex;
  position: relative;
}

.ui_navbar_item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  /* border-bottom:2rpx solid #ccc; 
  border-right:2rpx solid #ccc;  */
}

/* 選中後變字型顏色和背景顏色 */
.ui_navbar_item_on {
  /*選中後字型顏色*/
  color: rgb(190, 77, 77);
  /*選中後背景顏色*/
  background: #f1f1f1;
  /*選中後橫線*/
  border-bottom: 2rpx solid rgb(201, 107, 107);
  margin: 0rpx 20rpx 0rpx 20rpx;
}

所有實現的程式碼都給出來了,這裡就不放下載連結了

3、導航欄滑到一定程度就隱藏輪播圖

在這裡插入圖片描述

程式碼:

js

var that
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    autoplay: false, //是否自動播放
    circular: true, //是否採用銜接滑動
    indicatorDots: true, //是否顯示面板指示點
    scrollTop: '', //滑動的距離
    navFixed: false, //導航是否固定
    currentData: 0,
    // 輪播圖和小車 的圖片
    pictures: [
      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602154823228&di=b7d6be25877b4a6a221963b8172a32dd&imgtype=0&src=http%3A%2F%2Fpic15.nipic.com%2F20110630%2F1295091_123724627598_2.jpg",
      "https://m0.autoimg.cn/cardfs/upload/spec/11852/800x0_q87_autohomecar__y_20120127095328825264.jpg",
      "https://m0.autoimg.cn/cardfs/upload/spec/11852/800x0_q87_autohomecar__y_20120127095322804264.jpg",
      "https://m0.autoimg.cn/cardfs/upload/spec/10003/800x0_q87_autohomecar__y_20111119102503991264.jpg",

    ],
    // 電車中的圖片
    recommendPictures: [
      "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=225148521,438150860&fm=26&gp=0.jpg",
      "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=36293247,1325499932&fm=26&gp=0.jpg",
      "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1778493161,3668510566&fm=26&gp=0.jpg",
      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602154997262&di=cb0ca67c41063c6805940c7ba3430fc6&imgtype=0&src=http%3A%2F%2Fimage.cn.made-in-china.com%2F2f0j01HviacVUlvgkr%2F%25E8%25BE%25B9%25E4%25B8%2589%25E8%25BD%25AE%25E6%2591%25A9%25E6%2589%2598%25E8%25BD%25A6%2B%2528CJ750M1M%2529.jpg",
      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602154997262&di=6938091ecc99a9f6e1e41367e42925d4&imgtype=0&src=http%3A%2F%2Fimg11.360buyimg.com%2Fn1%2Fjfs%2Ft4243%2F146%2F607861919%2F136644%2Fb46eda48%2F58b6cb71N5f4c6e21.jpg"
    ]
  },

  /**
   * 生命週期函數--監聽頁面載入
   */
  onLoad: function (options) {
    that = this;

    /** 裝置資訊 */
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      },
    })
  },


  // 獲取當前滾軸的index
  bindchange: function (e) {
    console.log('獲取當前滾軸的index')

    that.setData({
      currentData: e.detail.current
    })
  },
  //點選切換,滾軸index賦值
  checkCurrent: function (e) {
    console.log('點選切換')

    console.log(e.target.dataset.current)
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },

  //監聽滑動
  layoutScroll: function (e) {
    this.data.scrollTop = this.data.scrollTop * 1 + e.detail.deltaY * 1;
    // console.log(this.data.scrollTop)
    // console.log(this.data.navFixed)

    /** 我這裡寫了固定值 如果使用rpx 可用query可以動態獲取其他的高度 然後修改這裡值 */
    /** 獲取方法參考檔案 */

    /** scrollTop 在模擬器上檢測不是太靈敏 可在真機上測試 基本上不會出現延遲問題 */
    var navtopHeight = 160;
    if (this.data.scrollTop <= -navtopHeight) {
      this.setData({
        navFixed: true
      })
    } else {
      this.setData({
        navFixed: false
      })
    }
  },
})

wxml

<view style="height: {{windowHeight}}px;">
  <scroll-view bindscroll='layoutScroll' scroll-y="true" style="height: 100vh;">
    <!-- swiper頂部圖片輪播切換 -->
    <swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" circular="{{circular}}" vertical="{{vertical}}"
      interval="{{interval}}" duration="{{duration}}" class='swiper-home'>
      <block wx:for="{{pictures}}" data-index="{{index}}" class='block-box' wx:key="{{index}}">
        <swiper-item>
          <image src='{{item}}' class='repair-img'></image>
        </swiper-item>
      </block>
    </swiper>

    <scroll-view scroll-x="true" class="nav {{navFixed? 'positionFixed':''}}">
      <!-- 導航欄 -->
      <view class='topTabSwiper'>
        <view class='one-tab' data-current="0" bindtap='checkCurrent'>
          <view data-current="0" class='{{currentData == 0 ? "tab-title-select" : "tab-title"}}'>小車</view>
          <view class='{{currentData == 0 ? "one-tab-line" : ""}}' data-current="0"></view>
        </view>
        <view class='center-tab' data-current="1" bindtap='checkCurrent'>
          <view data-current="1" class='{{currentData == 1 ? "tab-title-select" : "tab-title"}}'>摩托</view>
          <view class='{{currentData == 1 ? "two-tab-line" : ""}}' data-current="1"></view>
        </view>

        <view class='tab' data-current="2" bindtap='checkCurrent'>
          <view data-current="2" class='{{currentData == 2 ? "tab-title-select" : "tab-title"}}'>其他</view>
          <view class='{{currentData == 2 ? "one-tab-line" : ""}}' data-current="2"></view>
        </view>
      </view>

    </scroll-view>

    <!-- 切換0小車的內容 -->
    <view class='one-page' wx:if="{{currentData==0}}">
      <view wx:for="{{pictures}}" data-index="{{index}}" wx:key="{{index}}">
        <image src='{{item}}' class='repair-img'></image>
      </view>
    </view>

    <!-- 切換1摩托的內容 -->
    <view class='two-page' wx:if="{{currentData==1}}">
      <view wx:for="{{recommendPictures}}" data-index="{{index}}" wx:key="{{index}}">
        <image src='{{item}}' class='recommend-img'></image>
      </view>
    </view>

    <!-- 切換2其他的內容 -->
    <view class='three-page' wx:if="{{currentData==2}}">
      <text>其他的內容</text>
    </view>
  </scroll-view>
</view>

wxss

page {
  width: 100%;
  height: auto;
  background: #f3f3f3;
}
.swiper-home {
  height: 30vh;
  width: 100%;
}
.block-box {
  height: 30vh;
  width: 100%;
}
.repair-img {
  width: 100vw;
  height: 30vh;
}
.nav {
  background: white;
  z-index: 99;
  box-shadow: 0rpx -1.2rpx 10rpx 4rpx #dddddd99; /*for Android*/
  -webkit-box-shadow: 0px -0.6px 5px 2px #dddddd99;
}
.positionFixed {
  position: fixed;
  left: 0;
  top: 0;
  box-shadow: 0rpx -1.2rpx 10rpx 4rpx #dddddd99; /*for Android*/
  -webkit-box-shadow: 0px -0.6px 5px 2px #dddddd99;
}

/* 這個屬性特別重要!!不然樣式會崩掉 */
.topTabSwiper:after {
  content: "";
  clear: both;
  display: block;
}
.one-tab {
  width: 26vw;
  float: left;
  text-align: center;
  padding: 10rpx 0;
  height: 5.2vh;
  line-height: 4.6vh;
}
.tab-title-select {
  color: lightcoral;
  font-size: 32rpx;
}
.tab-title {
  font-size: 32rpx;
}
.one-tab-line {
  width: 10vw;
  border-bottom: 6rpx solid lightcoral;
  margin-left: 8vw;
  margin-top: 1vh;
  margin-bottom: 0.2vh;
}
.center-tab {
  width: 48vw;
  float: left;
  text-align: center;
  padding: 10rpx 0;
  height: 5.2vh;
  line-height: 4.6vh;
}
.two-tab-line {
  width: 10vw;
  border-bottom: 6rpx solid lightcoral;
  margin-left: 19vw;/*(48-10)/2讓紅線處在選項的中間*/
  margin-top: 1vh;
  margin-bottom: 0.2vh;
}
.tab {
  float: left;
  width: 26vw;
  text-align: center;
  padding: 10rpx 0;
  height: 5.2vh;
  line-height: 4.6vh;
}
.one-page {
  background: white;
  margin-top: 1vh;
}
.two-page{
    background: white;
  margin-top: 1vh;
}
.recommend-img{
  width: 100vw;
  height: 36vh;
}