微信小程序 bug 集中營

Create by jsliang on 2018-9-17 17:58:56
Recently revised in 2018-11-19 08:19:13


Hello 小夥伴們,如果覺得本文還不錯,記得給個 star , 你們的 star 是我學習的動力!GitHub 地址

寫在前面

 首個微信小程序實踐記錄:
 工作量: PSD 18 張 (導出的 JPG 30 張)
 耗時:12 個工作日
 總結1: 在頁面製作商,需要 3 周工作日(工作 15 天)搞定,前後端對接口另計。實際上,12 個工作日可以搞定所有頁面,但是應該往前鋪 1.5D 熟悉框架,往後鋪 1.5D 整理代碼。當然每個人的耗時可能不同,可根據個人實際情況進行調整。
 總結2:在 API 調用上,根據接口數量可能需要 7-12 個工作日進行 API 調用,難點表現在: 1. 接口不夠豐富,數據量不足; 2. 接口數據不夠正式真實,跟前面的假數據相差太大; 3. 接口可能沒法正常調用 等原因。故因根據小程序業務邏輯進行工作時長的報備。

這裏有 jsliang 微信小程序開發中遇到的所有坑,以及在填坑過程中的一些個人經驗。jsliang 利用這篇教程存儲一些常用的微信小程序開發技巧,方便查找。它可能教不了你什麼,但至少能省下你百度的功夫。

請結合 《目錄》 和 《返回目錄》 來進行跳轉,獲得更好的閱讀體驗。

 本文技術支持:Ansen江

注1:由於更新頻繁,有時候平臺上的文章版本可能沒有圖片或者目錄無法跳轉,所以小夥伴需要獲取最新資料的,請前往 GitHub:地址

注2:如果小夥伴使用的是手機版打開,那麼推薦小夥伴使用電腦打開,因爲各平臺的手機端大都不支持頁內跳轉,看起來比較費勁。


一 目錄

 目前已有 48 個坑。

請各位按目錄檢索時注意:
3.1、3.2、3.3…… 等二級目錄對應着一個章節。
3.1.1、3.1.2、3.1.3…… 等三級目錄將該二級目錄這個大章節詳細拆分成諸多小坑,方便查看。

注意!!!

 由於 SF 可能有字數限制,故 章節 12.1 之後的內容需要小夥伴前往 GitHub 地址查看

GitHub 地址


目錄
一 目錄
二 前言
三 填坑實戰
3.1 swiper 輪播圖 5
  3.1.1 行內樣式無效
  3.1.2 圖片樣式修改不了
  3.1.3 swiper 屬性值設置
  3.1.4 輪播圖圖片跳轉
  3.1.5 wx:key
  3.1.6 實戰代碼
3.2 tabBar 與 switchTab 3
  3.2.1 底部導航跳轉
  3.2.2 自定義底部導航
  3.2.3 自定義組件
3.3 px、rem 與 rpx 1
3.4 微信 web 開發者工具 2
  3.4.1 無法輸入中文
  3.4.2 無法滑動滾輪
3.5 組件與 API 2
  3.5.1 概念混淆:組件 VS API
  3.5.2 API 查詢不到對應的方法
3.6 flex 佈局 2
  3.6.1 基礎概念
  3.6.2 左右佈局
  3.6.3 混合佈局
3.7 background-image 套用本地圖片無效 1
3.8 <block> 與 <view> 1
3.9 搜索框 2
  3.9.1 margin-top 無法上浮
  3.9.2 改造 WeUI 搜索框
3.10 微信小程序分享 1
3.11 border-box 設置 1
3.12 自定義導航條 6
  3.12.1 WeUI 選項卡
  3.12.2 自定義選項卡效果與實現
  3.12.3 綁定事件如何傳遞數據
  3.12.4 不允許駝峯
  3.12.5 獲取 data 數據
  3.12.6 實現文字省略
3.13 黑科技:<modal> 2
  3.13.1 被遺棄的 <modal>
  3.13.2 四種彈窗寫法
3.14 小程序解析 HTML 6
  3.14.1 解析 HTML 的三種方法
  3.14.2 wxParse
  3.14.3 rich-text
  3.14.4 web-view
3.15 詭異的 open-type 1
3.16 <button>去樣式及其內嵌<image> 1
3.17 下拉刷新和上拉加載 2
3.18 獲取 input 的值 1
3.19 onLaunch 加載問題 2
  3.19.1 小程序執行順序
  3.19.2 路由守衛
3.20 request 封裝與 api 抽離 1
3.21 判斷數據是否讀取完 1
3.22 客服系統研究 1
3.23 文件在線預覽 2
3.24 儘量使用 ES6 1
3.25 視頻功能實現 1


二 前言

返回目錄

本文章原名【微信小程序 100 坑】

 微信小程序的開發教程,或許寫出來是非常受歡迎的。
 但是:

  • 第一,微信小程序是國內的,有中文文檔,雖然它的文檔說明有點坑,但好歹有文檔,閱讀理解對小夥伴們來說不是問題。
  • 第二, jsliang 的文筆並沒有想象中的那麼好,想想如果我帶你們走了一遍小程序開發,然後你們以爲是一條平坦路,結果碰到一堆坑坑窪窪,咋辦?最後的鍋,會不會到我背啊,可怕!

 所以,在這裏, jsliang 結合 “日常躺坑” ,先爲你解決小程序的 100 個坑!雖然現在可能還不夠,但是第一天我就碰到 4/5 個了,我想我可以幫你們躺完 100 個的!!!
 現在的微信開發者工具顯示的開發版本是:"libVersion": "2.0.4"
 如果你開發的版本已經解決了這個 bug ,或者你覺得這個 bug 還有其他解決方法,或者你覺得這個玩意還有其他 bug ,請告訴我,我會補充到這篇文檔上,順帶記上您的大名,謝謝!
QQ: 1741020489


三 填坑實戰

返回目錄

 這裏的坑:

  • 有的來源於微信自帶的開發文檔:小程序開發文檔。在文檔中,你會發現很多的樂趣!畢竟,你不知道什麼時候中文成爲了你的語言障礙~
  • 有的是開發中遇到的,然後結合大量的百度結果,進行的有效性總結。

 希望小夥伴在百度中或者無意看到這篇文章,請熟練使用瀏覽器的 Ctrl + F,查找需要的問題答案。


3.1 swiper 輪播圖

返回目錄

本組件目前已有 5 個坑,有興趣的小夥伴可以詳看。


  代碼來源於該地址:微信組件 swiper

 爲方便小夥伴查看,下面貼出原版代碼:

demo.wxml
<swiper indicator-dots="{{indicatorDots}}"
  autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}">
  <block wx:for="{{imgUrls}}">
    <swiper-item>
      <image src="{{item}}" class="slide-image" width="355" height="150"/>
    </swiper-item>
  </block>
</swiper>
<button bindtap="changeIndicatorDots"> indicator-dots </button>
<button bindtap="changeAutoplay"> autoplay </button>
<slider bindchange="intervalChange" show-value min="500" max="2000"/> interval
<slider bindchange="durationChange" show-value min="1000" max="10000"/> duration


demo.js
Page({
  data: {
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    indicatorDots: false,
    autoplay: false,
    interval: 5000,
    duration: 1000
  },
  changeIndicatorDots: function(e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function(e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function(e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function(e) {
    this.setData({
      duration: e.detail.value
    })
  }
})


 好的,上面就是微信官方文檔的演示代碼,如果你跟着演示代碼走了一遍碰到疑問的話,看看這裏我挖的土是不是能填好你的坑:


3.1.1 行內樣式無效

返回目錄

demo.wxml 中出現的 <image src="{{item}}" class="slide-image" width="355" height="150"/> 這行, widthheight 的行內屬性是忽悠老百姓的,它並沒卵用 !我們需要在 slide-image 這個 class 類中修改 widthheight。簡而言之,行內樣式都是騙人的,乖,我們還是去 demo.wxss 寫樣式吧~


3.1.2 圖片樣式修改不了

返回目錄

 在任何出現圖片的地方(包括但不限於輪播圖),如果你發現不僅行內寫法無效之外,還發現單純地給圖片加 class,去 *.wxss 寫樣式也無效的話。那麼,我建議小夥伴最好採用樣式加重法,即 .image-wrap .image 這種寫法格式,來確保圖片樣式能進行修改。詳細用法可看下文。


3.1.3 swiper 屬性值設置

返回目錄

swiper 屬性值。官方文檔說明:

圖片描述

 雖然,它的屬性名和屬性值是這麼說的。但是,用的時候,首先你需要在 demo.wxml 中的 swiper 綁定這個屬性名,然後在 demo.js 中設置其屬性值。值得注意的是,它的綁定值,稍微不同於 Vue, 需要設置 {{}} 形式。如果文字描述你看得不是很清楚,可以參照下面的代碼進行理解。


3.1.4 輪播圖圖片跳轉

返回目錄

 關於輪播圖的地址跳轉,在微信小程序的官網是沒用提及的,也是 jsliang 去百度查看了下,才知道怎麼設置(可能是我一開始就挑戰的難度太高了麼 -_-|| ),在下面 jsliang 貼出來代碼~想知道怎麼解決的可以去看看:首先,在 data 中設置 link ;然後,設置 navigator 導航遍歷 item.link


3.1.5 wx:key

返回目錄

 關於 wx:keywx:key 的作用是:當數據改變觸發渲染層重新渲染的時候,會校正帶有 key 的組件,框架會確保他們被重新排序,而不是重新創建,以確保使組件保持自身的狀態,並且提高列表渲染時的效率。但是,在其 swiper 中,小程序本身是沒有寫的,所以它會帶有 warning ,這裏也是個小坑, jsliang 也是百度了下也知道這件事:點我瞭解


3.1.6 實戰代碼

返回目錄

 下面給出這 5 個坑的解決代碼,如有不對,盡情指出:

index.wxml
<view class="carousel">
  <swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-color="#707071" indicator-active-color="#fff" circular="true">
    <!-- wx:key : 提高列表渲染效率 -->
    <block wx:for="{{imgUrls}}" wx:key="{{item.index}}">
      <swiper-item>
        <navigator url="{{item.link}}" hover-class="navigator-hover">
          <image src="{{item.url}}" class="slide-image" />
        </navigator>
      </swiper-item>
    </block>
  </swiper>
</view>


index.wxss
.carousel .slide-image {
  width: 100%;
  height: 420rpx;
}


index.js
Page({
  data: {
    imgUrls: [
      {
        link: '../index/index',
        url: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      },
      {
        link: '../demo/demo',
        url: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      },
      {
        link: '../logs/logs',
        url: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg'
      }
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000
  }
})


3.2 tabBar 與 switchTab

返回目錄

本組件目前已有 3 個坑,有興趣的小夥伴可以詳看。

 tabBar :底部菜單欄,需要在 app.json 中設置。使用方法:見下文。
 navigator :導航切換。使用方法:地址
 switchTab :控制 tabBar 的切換。使用方法:地址


3.2.1 底部導航跳轉

返回目錄

 在這裏,我們講下 tabBar 的坑,如果你在 app.json 中設置了 tabBar

app.json
"tabBar": {
    "list": [{
      "pagePath": "pages/index/index",
      "text": "首頁",
      "iconPath": "./public/index_tabBar1_nor.png",
      "selectedIconPath": "./public/index_tabBar1.png"
    }, {
      "pagePath": "pages/demo/demo",
      "text": "發現",
      "iconPath": "./public/index_tabBar2_nor.png",
      "selectedIconPath": "./public/index_tabBar2.png"
    }, {
      "pagePath": "pages/logs/logs",
      "text": "我的",
      "iconPath": "./public/index_tabBar3_nor.png",
      "selectedIconPath": "./public/index_tabBar3.png"
    }]
  }


 那麼,我們就需要通過設置 switchTab 來控制底部導航的跳轉,而不能通過 navigator 來跳轉:

demo.wxml
<view>
  <button bindtap="linkTo">Hello</button>
</view>


demo.js
linkTo: function () {
  wx.switchTab({
    url: '../index/index'
  });
},


3.2.2 自定義底部導航

返回目錄

 那麼問題又來了,當我們切換到子頁面的時候,我們發現 tabBar 這個底部導航欄不見了,然後問了下 Ansen江 ,他說之前是整個小程序都有的,有些頁面還要想方設法去隱藏。
 但是現在嘛……它沒了!沒了啊!!!在微信小程序的文檔沒看到有喚起底部導航條的方法,難道我要做一個導航條了麼 -_-||
 回答是:yes!
 所以,下面給出該底部導航條 tabBar 的實現情況和代碼片段:

圖片描述

注:圖片寬高均爲 54rpx

*.wxml

<view class="nav">
  <view class="nav-home" bindtap="goHome">
    <image src="../../public/index_productDetail_icon_home.png"></image>
    <text>首頁</text>
  </view>
  <view class="nav-service">
    <image src="../../public/index_productDetail_icon_service.png"></image>
    <text>在線諮詢</text>
  </view>
  <view class="nav-phone" bindtap="callWaiter">
    <image src="../../public/index_productDetail_icon_phone.png"></image>
    <text>電話諮詢</text>
  </view>
  <navigator url="../indexPurchaseProduct/indexPurchaseProduct">
    <view class="nav-buy">
      <text>立即訂購</text>
    </view>
  </navigator>
</view>


*.wxss
.nav {
  display: flex;
  justify-content: space-around;
  font-size: 20rpx;
  border: 1px solid #ccc;
  position: fixed;
  bottom: 0;
  background: #fff;
}
.nav view {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.nav image {
  width: 54rpx;
  height: 54rpx;
}
.nav text {
  margin-top: 7rpx;
}
.nav-home {
  border-right: 1px solid #ccc;
  width: 130rpx;
  padding-top: 5rpx;
}
.nav-service {
  border-right: 1px solid #ccc;
  width: 130rpx;
  padding-top: 5rpx;
}
.nav-phone {
  width: 130rpx;
  padding-top: 5rpx;
}
.nav-buy {
  background: #eb333e;
  color: #fff;
  width: 360rpx;
  height: 98rpx;
  line-height: 80rpx;
  font-size: 34rpx;
}


*.js
callWaiter: function(res) {
  wx.makePhoneCall({
    phoneNumber: '13264862250',
    success: function(res) {
      console.log("撥打成功");
      console.log(res);
    },
    fail: function(res) {
      console.log("撥打失敗");
      console.log(res);
    },
    complete: function(res) {
      console.log("撥打完成");
      console.log(res);
    }
  })
},
goHome: function() {
  wx.switchTab({
    url: '../index/index'
  })
},


3.2.3 自定義組件

返回目錄

 在最近的工作中,又發現一個小問題:

圖片描述

 像這個導航條,它需要根據頁面所在的模塊,動態地展示不同位置的狀態爲活躍,而且它是需要在多個頁面重複出現的,如果每個頁面我都要複製粘貼一遍,到時候要修改起來的時候,麻煩不說,最重要的是,它可能影響我前端的性能了,能不能直接將其封裝起來呢?

 自定義組件:鏈接

 是的,發現在小程序文檔中是存在這個東西的。當然,至於過程中我百度了幾篇文章來輔助寫出下面的代碼,你猜?

 子組件寫法

navBar.wxml
<!-- 底部導航條 -->
<view class="navBar">
  <view class="navBar-home" bindtap='goHome'>
    <image wx:if="{{homeActive}}" src="../../public/index_tabBar1.png"></image>
    <image wx:if="{{!homeActive}}" src="../../public/index_tabBar1_nor.png"></image>
    <text>首頁</text>
  </view>
  <view class="navBar-explore" bindtap='goExplore'>
    <image wx:if="{{exploreActive}}" src="../../public/index_tabBar2.png"></image>
    <image wx:if="{{!exploreActive}}" src="../../public/index_tabBar2_nor.png"></image>
    <text>發現</text>
  </view>
  <view class="navBar-user" bindtap='goUser'>
    <image wx:if="{{userActive}}" src="../../public/index_tabBar3.png"></image>
    <image wx:if="{{!userActive}}" src="../../public/index_tabBar3_nor.png"></image>
    <text>我的</text>
  </view>
</view>


navBar.wxss
/* 底部導航條 */
.navBar {
  width: 100%;
  padding: 18rpx 0;
  border-top: 1rpx solid #cccccc;
  display: flex;
  justify-content: space-around;
  position: fixed;
  bottom: 0;
  background: #fff;
}
.navBar image {
  width: 55rpx;
  height: 55rpx;
}
.navBar view {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 20rpx;
  color: #999999;
}
.navBar-user text {
  color: #d0a763;
}


navBar.js
// pages/componentNavBar/navBar.js
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    homeActive: {
      type: Boolean,
      value: false
    },
    exploreActive: {
      type: Boolean,
      value: false
    },
    userActive: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 組件的初始數據
   */
  data: {

  },

  /**
   * 組件的方法列表
   */
  methods: {
    // 返回首頁
    goHome: function (e) {
      wx.switchTab({
        url: '../index/index',
      })
    },
    // 返回發現頁 
    goExplore: function (e) {
      wx.switchTab({
        url: '../explore/explore',
      })
    },
    // 返回我的頁面
    goUser: function (e) {
      wx.switchTab({
        url: '../user/user',
      })
    },
    showCode: function(e) {
      console.log(e);
      let that = this;
      console.log(that.data);
    }
  }
})


navBar.json
{
  "component": true,
  "usingComponents": {}
}


 然後,在父組件的使用,只需要:

*.wxml
<view>
  <navBar userActive="{{userActive}}"></navBar>
</view>


*.json
{
  "usingComponents": {
    "navBar": "../componentNavBar/navBar"
  }
}


*.js
data: {
  userActive: true
},


 怎樣?這就是自定義組件的寫法,是不是覺得特好用涅,一次寫完,終身受用。


3.3 px、rem 與 rpx

返回目錄

本節目前已有1個坑,有興趣的小夥伴可以詳看。

 在微信中,它自帶了一套屬於自己的單位:rpxrpx 不同於之前我們認識的 pxremem ,如果你的設計稿是 750 px 的,那麼很容易的, 1px = 1rpx ,但是,如果設計稿不是 750 px ,那麼將造成一個 bug ,至於這個 bug 如何解決……
 -_-|| 誰知道呢……要不先把UI設計師宰了?
 知識補充:關於 rpx


3.4 微信 web 開發者工具

返回目錄

本節目前已有 2 個坑,有興趣的小夥伴可以詳看。


3.4.1 無法輸入中文

返回目錄

 如果你在開發過程中,發現只能寫英文了,而中文無法輸入了,千萬別急,也別怪輸入法出 bug 了,你只需要:重啓開發工具。


3.4.2 無法滑動滾輪

返回目錄

 如果你某時刻,突然發現你沒法滾動代碼進行查看,而是需要拖動滾動條才行,請別怪你的鼠標,你可以去瀏覽器打開一篇文章看看,enm...你的鼠標還是好的~所以,請:重啓開發工具。


3.5 組件與 API

返回目錄

本節目前已有 2 個坑,有興趣的小夥伴可以詳看。

3.5.1 概念混淆:組件 VS API

返回目錄

 首先,科普下 組件 與 API 是什麼:

  • 組件:對數據和方法的封裝,使用組件可以實現拖放式編程、快速的屬性處理以及真正的面向對象的設計【百度百科】。那麼,可以理解爲:開發中常用的一些部件,我們都可以封裝起來,然後在需要的時候拿來用,即爲組件。
  • API:預先定義的函數,提供應用程序與開發人員無需訪問源碼,基於某軟件或硬件得以訪問一組例程的能力【百度百科】。就是說已經寫好的一些 Function 或者後端接口,前端直接調用就行了。

 但是,在微信小程序官方文檔中,組件與API,拆分地有點不科學。
 例如:輪播圖底部導航條

  • 一個在組件中,一個在 API 中;
  • 一個在 wxmlwxssjs 中要設置對應的參數,一個只需要在 app.json 中設置就行。

 可能微信小程序考慮到底部導航條不應該有太大的變化(例如讓你修改太多樣式或者 js ),所以將導航條內嵌至源碼中了。
 但是,這可能導致什麼重要影響嗎?是的,如果底部導航條需要進行修改呢?例如:3.2.3 自定義組件。這樣的情況下,我們的開發時間就有所增加了。


3.5.2 API 查詢不到對應的方法

返回目錄

 如果小夥伴你經常有去看微信小程序官方文檔的話,那麼你一定會有一件事需要吐槽,那就是:
 明明上次我見到過某個 API 實現了我需要做的功能,但是改天我回去查找的時候,它卻提示我沒有這個玩意,這是什麼鬼?!
 是的,跟我們 3.13 黑科技:<modal> 這一章中講到的 <modal> 這個黑科技一樣,有時候官方文檔也不是萬能的,它總會有這樣那樣的毛病,導致我們找不到需要的東西,只能去百度了 -_-||


3.6 flex 佈局

返回目錄

本節目前已有 3 個坑,有興趣的小夥伴可以詳看。

 Flex佈局又稱彈性佈局,在小程序開發中比較適用。但是由於 jsliang 之前沒怎麼用過 Flex 佈局,所以在這裏咱們特意去踩下坑,充實下自己。【小程序開發之頁面佈局】【阮一峯-Flex 佈局教程】
 在我們佈局頁面的時候,最好看看 阮一峯 的教程,平時遇到佈局的問題的時候,我都習慣去上面 阮一峯 的文章看看:


3.6.1 基礎概念

返回目錄

 基礎概念:地址

  <!-- 設置 flex 佈局 -->
  display: flex;

  <!-- 
    1、決定主軸的方向
    row - (默認)水平方向,起點在左端
    row-reverse - 水平方向,起點在右端
    column - 垂直方向,起點在上沿
    column-reverse - 垂直方向,起點在下沿
   -->
  flex-direction: row | row-reverse | column | column-reverse;
  
  <!-- 
    2、一條軸線(一行)排不下時如何解決
    nowrap - (默認)不換行
    warp - 換行,第一行在上方
    wrap-reverse - 換行,第一行在下方
   -->
  flex-wrap: nowrap | wrap | wrap-reverse;
  
  <!-- 
    3、flex-flow = flex-direction + flex-wrap。即 flex-flow 是這兩個屬性的合集
    row nowrap - (默認)水平方向,起點在左端,不換行
   -->
  flex-flow: <flex-direction> || <flex-wrap>;
  
  <!-- 
    4、justify-content 定義項目在主軸上的對齊方式
    flex-start - 左邊對齊
    flex-end - 右邊對齊
    center - 居中對齊
    space-between - 兩端對齊,空格在中間
    space-around - 空格環繞
   -->
  justify-content: flex-start | flex-end | center | space-between | space-around;
  
  <!-- 
    5、align-items 定義項目在交叉軸上如何對齊
    flex-start - 頂部對齊,即文字圖片等頂部同一條線上
    flex-end - 底部對其,即文字圖片等底部在同一條線上
    center - 中間對其,即文字圖片不管多高,都拿它們的中間放在同一條線上
    stretch - 將文字圖片充滿整個容器的高度,強制統一
    baseline - 將每項的第一行文字做統一在一條線上對齊
   -->
  align-items: flex-start | flex-end | center | stretch | baseline;
  
  <!-- 
    6、align-content 定義多根軸線的對齊方式。如果只有一根軸線(只有一行),該屬性不起作用
    flex-start - 這幾行頂部對齊
    flex-end - 這幾行底部對齊
    center - 這幾行居中對齊
    stretch - 這幾行進行擴展或者縮放,從而填滿容器高
    space-between - 這幾行中間使用空格進行填充
    space-around - 這幾行兩邊及中間進行填充
   -->
  align-content: flex-start | flex-end | center | space-between | space-around | stretch;


3.6.2 左右佈局

返回目錄

 實現效果如下:

圖片描述

 如圖,這是我們要實現的左右佈局效果。那麼,在微信小程序要怎麼做呢?

*.wxml
<view class="top-recommended-headlines">
  <view class="top-recommended-headlines-left">
    <text>熱門推薦</text>
  </view>
  <view>
    <image src="../../public/index_top_recommended_headlines.png"></image>
  </view>
  <view class="top-recommended-headlines-right">
    <navigator url="../indexProduct/indexProduct">查看全部 ></navigator>
  </view>
</view>


*.wxss
.top-recommended-headlines {
  display: flex;
  align-items: flex-end;
  height: 31rpx;
  line-height: 31rpx;
  margin-bottom: 10rpx;
}
.top-recommended-headlines-left text {
  font-size: 32rpx;
  font-weight: bold;
}
.top-recommended-headlines image {
  width: 366rpx;
  height: 31rpx;
  margin-left: 10rpx;
}
.top-recommended-headlines-right navigator {
  font-size: 26rpx;
  color: #a9a9a9;
  margin-left: 50rpx;
}


3.6.3 混合佈局

返回目錄

 實現效果如下:

圖片描述

 如圖,這是我們要實現的左右佈局效果。那麼,在微信小程序要怎麼做呢?

*.wxml
<view class="weui-tab__content-item3" wx:for="{{tabs3Content}}" wx:key="{{item.index}}">
  <navigator url="../indexProductArticle/indexProductArticle">
    <view class="weui-tab__content-item3-question">
      <image src="../../public/index_productDetail_icon_question.png"></image>
      <text>{{item.title}}</text>
    </view>
    <view class="weui-tab__content-item3-answer">
      <image src="../../public/index_productDetail_icon_answer.png"></image>
      <text>{{item.content}}</text>
    </view>
    <view class="weui-tab__content-item3-detail">
      <text class="weui-tab__content-item3-detail-datatime">{{item.datatime}}</text>
      <text class="weui-tab__content-item3-detail-reader">{{item.reader}}閱讀</text>
      <text class="weui-tab__content-item3-detail-label">#{{item.label}}#</text>
    </view>
  </navigator>
  <view class="weui-tab__content-item3-gap">
    <image src="../../public/index_productDetail_gap.png"></image>
  </view>
</view>


*.wxss
.weui-tab__content-item3 {
  padding-left: 30rpx;
  padding-right: 30rpx;
  margin-top: -10rpx;
  margin-bottom: 10rpx;
}
.weui-tab__content-item3:first-child {
  padding: 40rpx 30rpx 0;
}
.weui-tab__content-item3-question image {
  width: 30rpx;
  height: 30rpx;
}
.weui-tab__content-item3-question text {
  font-size: 30rpx;
  line-height: 46rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}
.weui-tab__content-item3-answer image {
  width: 30rpx;
  height: 30rpx;
}
.weui-tab__content-item3-answer text {
  font-size: 26rpx;
  line-height: 42rpx;
  color: #a9a9a9;
  margin-left: 10rpx;
}
.weui-tab__content-item3-detail {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #a9a9a9;
}
.weui-tab__content-item3-detail-label {
  color: #d0a763;
}
.weui-tab__content-item3-gap image {
  width: 100%;
  height: 30rpx;
}


*.js
tabs3Content: [
  {
    title: '員工發明創造是否屬於職務發明的認證標準?',
    content: '隨着企業對知識產權在企業發展中核心競爭力的認識力提高,企業保護自身知識產權的意識不斷增強,使其技術得......',
    datatime: '2018-03-05',
    reader: '2081',
    label: '知識產權'
  }
]


3.7 background-image 套用本地圖片無效

返回目錄

本節目前已有 1 個坑,有興趣的小夥伴可以詳看。

 在小程序中,如果你使用 wxss,你是可以發現有 background-image 的提示的。但是,如果你設置它的背景圖是本地圖片,你會發現,它是不生效的。
 解決方案:

  1. 在使用背景圖片的時候用網絡圖片,就是用外鏈的形式,比如你將這張圖片放到你的服務器,如:https://xxxx/xxx.jpg
  2. 將背景圖片使用編碼base64進行轉換,可以在這個網址進行 點我前往 轉換,如:background-image: url("轉換後得到的編碼文本"),如果多次使用的話可以將該值設置爲全局變量,再在js文件進行引用即可。
  3. 使用 image 組件 + position 定位而不是使用 background-image


3.8 <block> 與 <view>

返回目錄

本節目前已有 1 個坑,有興趣的小夥伴可以詳看。

 兩者的區別是,<view> 是一個組件,會在頁面上做渲染;<block> 不是一個組件,它僅僅是一個包裝元素,只接受控制屬性,不會在頁面中做任何渲染。
 所以,如果你僅僅是需要包裹,而不是渲染一個層,可以使用 <block> 提升性能。


3.9 搜索框

返回目錄

本節目前已有 2 個坑,有興趣的小夥伴可以詳看。


3.9.1 margin-top 無法上浮

返回目錄

 首先,我們要實現的效果是:

圖片描述

 然後, jsliang 的想法是:

*.wxml
<view class="search">
  <input class="search-product-input" bindinput="bindKeyInput" auto-focus maxlength='10'></input>
  <label class="search-placeholder">
    <image class="search-placeholder-icon" src="../../public/index_indexProduct_icon_search.png"></image>
    <text class="search-placeholder-text">搜索產品</text>
  </label>
  <view></view>
</view>


*.wxss
.search {
  height: 100rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  position: relative;
}
.search-product-input {
  background: #f5f5f5;
  width: 650rpx;
  height: 65rpx;
  border-radius: 30rpx;
  font-size: 30rpx;
  padding-left: 20rpx;
}
.search-placeholder {
  font-size: 26rpx;
  text-align: center;
  margin-top: -65rpx;
  z-index: 2;
}
.search-placeholder-icon {
  width: 24rpx;
  height: 24rpx;
}
.search-placeholder-text {
  margin-left: 10rpx;
}


 你注意到了嗎?在 *.wxml 中, jsliang 設置了個空的 <view> ,如果你把這個 <view> 去掉,你會驚奇地發現,它……下來了……

圖片描述

 好吧,可能有其他的實現方式,但是如果你下次使用這種方式,注意上面這個坑~


3.9.2 改造 WeUI 搜索框

返回目錄

 回頭看了下 WeUI 的實現方式,發現跟我的思路是挺像的,關於 input 的實現方式,現在依據 WeUI ,成功實現了輸入框:

圖片描述

 源碼奉上:

*.wxml
<!-- 搜索框 -->
<view class="search">
  <view class="weui-search-bar">
    <view class="weui-search-bar__form {{inputShowed ? 'form-border' : ''}}">
      <view class="weui-search-bar__box">
        <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
        <input type="text" class="weui-search-bar__input" placeholder="搜索" value="{{inputVal}}" focus="{{inputShowed}}" bindinput="inputTyping" />
        <view class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput">
          <icon type="clear" size="14"></icon>
        </view>
      </view>
      <label class="weui-search-bar__label" hidden="{{inputShowed}}" bindtap="showInput">
        <icon class="weui-icon-search" type="search" size="14"></icon>
        <view class="weui-search-bar__text">搜索</view>
      </label>
    </view>
    <view wx:if="{{inputVal.length <= 0}}" class="weui-search-bar__cancel-btn" hidden="{{!inputShowed}}" bindtap="hideInput">取消</view>
    <view wx:if="{{inputVal.length > 0}}" class="weui-search-bar__submit-btn" hidden="{{!inputShowed}}" bindtap="searchInput">搜索</view>
  </view>
</view>


*.js
Page({
  data: {
    inputShowed: false,
    inputVal: ""
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  }
})


*.wxss
.search {
  height: 100rpx;
  padding: 18rpx 30rpx;
}
.weui-search-bar {
  padding: 0;
  background-color: #fff;
  border-top: none;
  border-bottom: none;
  height: 64rpx;
}
.weui-search-bar__form {
  border: none;
}
.form-border {
  border: 1rpx solid #f5f5f5;
  background: #f5f5f5;
}
.weui-search-bar__label {
  background: #f5f5f5;
  border-radius: 30rpx;
}
.weui-search-bar__cancel-btn {
 font-size: 26rpx; 
 background: rgb(8, 202, 186);
 color: #fff;
 padding: 2rpx 20rpx 0 20rpx;
 border-radius: 10rpx;
}
.weui-search-bar__submit-btn {
  font-size: 26rpx; 
  background: rgb(8, 200, 248);
  color: #fff;
  padding: 10rpx 20rpx 0 20rpx;
  border-radius: 10rpx;
}


3.10 微信小程序分享

返回目錄

本節目前已有 1 個坑,有興趣的小夥伴可以詳看。

 官方文檔:地址
 在這裏,提醒廣大小夥伴注意了,注意了,注意了!重要的事說三遍。
 當你新建 page 的時候,微信 web 開發者工具會自動幫你添加分享事件:

/**
  * 用戶點擊右上角分享
  */
onShareAppMessage: function (res) {
  // 實現分享功能
  return {
    title: this.data.productName,
    path: '/pages/indexProductDetail.js?productId=' + this.data.productId,
    imageUrl: this.data.videoImageSrc,
    success: (res) => {
      console.log("分享成功~");
    },
    fail: (res) => {
      console.log("分享失敗~");
    }
  }
}


 所以,如果你在前面定義了,它會在最下面偷偷幫你清空,然後你就覺得無法自定義分享事件……
 是的,jsliang 打死都不承認這是我自己的鍋,新手注意!新手注意!!新手注意!!!


3.11 border-box 設置

返回目錄

本節目前已有 1 個坑,有興趣的小夥伴可以詳看。

 熟知盒模型的小夥伴應該知道,盒模型有兩種計算方式:

  1. box-sizing: border-box;
  2. box-sizing: content-box;

 在 border-box 中,整個 view 的寬、高,包括 marginpaddingborder
 而在 content-box 中,整個 view 的寬、高,則不包括上面元素。

圖片描述

 如上圖,如果一個 view ,你的代碼如下:

view {
  box-sizing: border-box;
  margin: 10rpx;
  width: 100rpx;
  height: 100rpx;
  padding: 10rpx;
}


 那麼,你的整個寬高還是 100rpx
 但是,如果你的代碼如下:

view {
  box-sizing: content-box;
  margin: 10rpx;
  width: 100rpx;
  height: 100rpx;
  padding: 10rpx;
}


 那麼,你的整個盒子寬高是 120rpx

 如果你在設計頁面中,發現內容區被撐爆了,那麼,請檢查下現在的 border-box 是什麼。


3.12 自定義選項卡

返回目錄

本節目前已有 6 個坑,有興趣的小夥伴可以詳看。


3.12.1 WeUI 選項卡

返回目錄

 使用 WeUI 的導航條,首先需要引用 WeUI 的 CSS 樣式:地址

 下載 weui.wxss 並在 app.wxss 中引用即可

app.wxss
/* 引用WeUI */
@import 'weui.wxss';


 然後,我們直接往頁面加入它的選項卡並根據項目需求修改其樣式:


*.wxml
<view class="tab">
  <view class="weui-tab">
    <view class="weui-navbar">
      <block wx:for="{{tabs}}" wx:key="*this">
        <view id="{{index}}" class="weui-navbar__item {{activeIndex == index ? 'weui-bar__item_on' : ''}}" bindtap="tabClick">
          <view class="weui-navbar__title">{{item}}</view>
        </view>
      </block>
      <view class="weui-navbar__slider" style="left: {{sliderLeft}}px; transform: translateX({{sliderOffset}}px); -webkit-transform: translateX({{sliderOffset}}px);"></view>
    </view>
    <view class="weui-tab__panel">
      <!-- 全部 -->
      <view class="weui-tab__content" hidden="{{activeIndex != 0}}">
        <view class="weui-tab__content-item1">
          <text>全部</text>
        </view>
      </view>
      <!-- 已付款 -->
      <view class="weui-tab__content" hidden="{{activeIndex != 1}}">
        <view class="weui-tab__content-item2">
          <text>已付款</text>
        </view>
      </view>
      <!-- 待付款 -->
      <view class="weui-tab__content" hidden="{{activeIndex != 2}}">
        <view class="weui-tab__content-item3">
          <text>待付款</text>
        </view>
      </view>
    </view>
  </view>
</view>


*.wxss
.tab {
  font-size: 26rpx;
}
.tab image {
  width: 173rpx;
  height: 29rpx;
}
.weui-navbar {
  border-top: 1rpx solid #efefef;
  border-bottom: 1rpx solid #efefef;
}
.weui-navbar__slider {
  background: #d0a763;
  width: 4em;
}
.weui-navbar__item.weui-bar__item_on {
  color: #d0a763;
}
.weui-tab__content {
  margin-bottom: 100rpx;
}


*.js
var sliderWidth = 52; // 需要設置slider的寬度,用於計算中間位置

Page({

  /**
   * 頁面的初始數據
   */
  data: {
    // 選項卡導航
    tabs: ["全部", "已付款", "待付款"],
    activeIndex: 1,
    sliderOffset: 0,
    sliderLeft: 0,
  },
  // 選項卡切換
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },

  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    // 計算搜索框活躍條
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
  }
})

2018-11-15:新增一個 bug 修復,就是在第一個 tab 能流暢切換的情況下,第二個及其他的 tab,需要多次滑動才能上拉加載。這時候,只需要在 weui-tab__content 這個類新增三行代碼就可以解決該問題:

*.css
.weui-tab__content {
  padding: 30rpx 30rpx 0;
  box-sizing: border-box;
  height: 100%;
  overflow: hidden;
}


3.12.2 自定義選項卡效果與實現

返回目錄

 自定義選項卡的代碼實現:

 實現效果圖如下:

圖片描述

 實現代碼如下:

*.wxml
<view>
  <view class="weui-tab__nav">
    <text wx:for="{{tabs2Nav}}" wx:key="item.index" class="{{item.state == 1 ? 'weui-tab__nav-active' : ''}}" bindtap="tabs2NavClick" data-labelId="{{item.id}}">{{item.label}}</text>
  </view>
  <view class="weui-tab__content-item2" wx:for="{{tabs2Content}}" wx:key="{{item.index}}">
    <view class="weui-tab__content-item-descritpion">
      <view class="{{item.type == 1 ? 'weui-tab__content-item-icon-type' : 'hide'}}">
        <image src="../../public/index_productDetail_icon_word.png"></image>
      </view>
      <view class="{{item.type == 2 ? 'weui-tab__content-item-icon-type' : 'hide'}}">
        <image src="../../public/index_productDetail_icon_excel.png"></image>
      </view>
      <view class="{{item.type == 3 ? 'weui-tab__content-item-icon-type' : 'hide'}}">
        <image src="../../public/index_productDetail_icon_ppt.png"></image>
      </view>
      <view class="{{item.type == 4 ? 'weui-tab__content-item-icon-type' : 'hide'}}">
        <image src="../../public/index_productDetail_icon_pdf.png"></image>
      </view>
      <view class="weui-tab__content-item-descritpion-content">
        <text class="weui-tab__content-item-descritpion-content-title">{{item.title}}</text>
        <view class="weui-tab__content-item-descritpion-content-datatime">
          <text class="weui-tab__content-item-descritpion-content-datatime1">發佈時間:{{item.datatime}}</text>
          <text class="{{item.effectiveTime ? 'weui-tab__content-item-descritpion-content-datatime2' : 'hide'}}">生效時間:{{item.effectiveTime}}</text>
        </view>
      </view>
    </view>
    <view class="weui-tab__content-item-download-state" bindtap='downloadFile' data-url="{{item.url}}">
      <image src="../../public/index_productDetail_icon_undown.png"></image>
    </view>
  </view>
</view>


*.wxss
.weui-tab__nav {
  background: #f5f5f5;
  border: 1rpx 0rpx solid #e6e6e6;
  height: 90rpx;
  padding: 17rpx 41rpx;
  display: flex;
  justify-content: space-between;
}
.weui-tab__nav text {
  border-radius: 56rpx;
  height: 56rpx;
  line-height: 56rpx;
  padding: 15rpx 23rpx;
  font-size: 26rpx;
  font-weight: bold;
}
.weui-tab__nav-active {
  color: #fefefe;
  background: #d0a763;
}
.weui-tab__content-item2 {
  display: flex;
  justify-content: space-between;
  padding: 25rpx 30rpx;
}
.weui-tab__content-item-descritpion {
  display: flex;
  justify-content: space-between;
}
.weui-tab__content-item-descritpion image {
  width: 60rpx;
  height: 70rpx;
}
.hide {
  display: none;
}
.weui-tab__content-item-descritpion-content {
  margin-left: 26rpx;
}
.weui-tab__content-item-descritpion-content-title {
  font-size: 28rpx;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.weui-tab__content-item-descritpion-content-datatime {
  font-size: 22rpx;
  color: #bbb;
}
.weui-tab__content-item-descritpion-content-datatime1 {
  margin-right: 35rpx;
}
.weui-tab__content-item-download-state image {
  width: 64rpx;
  height: 64rpx;
}


*.js
data: {
  tabs2Nav: [
    {
      id: '1',
      label: '法律大全',
      state: 1
    },
    {
      id: '2',
      label: '合同模板',
      state: 0
    },
    {
      id: '3',
      label: '民事',
      state: 0
    },
    {
      id: '4',
      label: '行政',
      state: 0
    },
    {
      id: '5',
      label: '執行',
      state: 0
    }
  ],
  tabs2Content: [
    {
      title: '中華人名共和國民用航空法(2015年...).doc',
      url: 'https://wxmcard.imusic.cn/testfordocdownload.doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    },
    {
      title: '原生申訴表格.xls',
      url: 'https://wxmcard.imusic.cn/testfordocdownload.doc',
      datatime: '2018-01-26',
      type: '2'
    },
    {
      title: '法律常識大彙集及範例.ppt',
      url: 'https://wxmcard.imusic.cn/testforpptdownload.pptx',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '3'
    },
    {
      title: '事業單位法律基礎知識總結.pdf',
      url: 'https://wxmcard.imusic.cn/testforpdfdownload.pdf',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '4'
    }
  ],

  // 選項卡第二屏分組
  tabs2Content1: [
    {
      title: '中華人名共和國民用航空法(2015年...).doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    },
    {
      title: '原生申訴表格.xls',
      datatime: '2018-01-26',
      type: '2'
    },
    {
      title: '法律常識大彙集及範例.ppt',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '3'
    },
    {
      title: '事業單位法律基礎知識總結.pdf',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '4'
    }
  ],
  tabs2Content2: [
    {
      title: '合同模板.doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    }
  ],
  tabs2Content3: [
    {
      title: '民事合同模板.doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    }
  ],
  tabs2Content4: [
    {
      title: '行政合同模板.doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    }
  ],
  tabs2Content5: [
    {
      title: '執行合同模板.doc',
      datatime: '2018-01-26',
      effectiveTime: '2018-01-26',
      type: '1'
    }
  ]
},
// 選項卡2切換
tabs2NavClick: function(e) {
  var that = this;
  console.log("完整的數據是:");
  console.log(that.data.tabs2Nav);
  
  console.log("點擊的標籤是:");
  console.log(e.currentTarget.dataset.labelid);

  var newTabs2Content;

  console.log("正在經歷的標籤是:");
  for(var i=0; i<that.data.tabs2Nav.length; i++) {
    console.log(that.data.tabs2Nav[i].id);
    that.data.tabs2Nav[i].state = 0;
    if (that.data.tabs2Nav[i].id == e.currentTarget.dataset.labelid) {
      that.data.tabs2Nav[i].state = 1;
      console.log("將改變的標籤是:");
      console.log(that.data.tabs2Nav[i]);

      // 改變內容
      var changeContentName = "tabs2Content" + (i + 1);
      if (changeContentName == "tabs2Content1") {
        console.log(that.data.tabs2Content1);
        newTabs2Content = that.data.tabs2Content1;
      } else if (changeContentName == "tabs2Content2") {
        newTabs2Content = that.data.tabs2Content2;
      } else if (changeContentName == "tabs2Content3") {
        newTabs2Content = that.data.tabs2Content3;
      } else if (changeContentName == "tabs2Content4") {
        newTabs2Content = that.data.tabs2Content4;
      } else {
        newTabs2Content = that.data.tabs2Content5;
      }

      console.log("希望轉換內容到:");
      console.log(changeContentName);
    }
  }

  this.setData({
    tabs2Nav: that.data.tabs2Nav,
    tabs2Content: newTabs2Content
  })
},

注意

 由於 SF 可能有字數限制,故 章節 12.1 之後的內容需要小夥伴前往 GitHub 地址查看

GitHub 地址


<img alt="知識共享許可協議" style="border-width:0" src="https://i.creativecommons.org...; />
jsliang 的文檔庫樑峻榮 採用 知識共享 署名-非商業性使用-相同方式共享 4.0 國際 許可協議進行許可。
基於https://github.com/LiangJunro...上的作品創作。
本許可協議授權之外的使用權限可以從 https://creativecommons.org/l... 處獲得。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章